【问题标题】:SoftDelete : System.Collections.Generic.List<##.##.Employee>' to 'Microsoft.AspNetCore.Mvc.IActionResult'SoftDelete:System.Collections.Generic.List<##.##.Employee>\' 到 \'Microsoft.AspNetCore.Mvc.IActionResult\'
【发布时间】:2022-11-24 02:48:31
【问题描述】:

我尝试执行软删除时出错

无法将类型“System.Collections.Generic.List<##.##.Employee>”隐式转换为“Microsoft.AspNetCore.Mvc.IActionResult”。

这是我的索引,我尝试使用 ToList() 和 ToList 但它不起作用

public IActionResult Index()
        {
            var employees = _dbContext.Employees.Where(x => x.status == '1')
                   .ToList();
                return employees;
        }

我的数据库上下文

public class DataContext : DbContext
{

   
    public DataContext(DbContextOptions options) : base(options)
    {
    }


    public DbSet<Employee> Employees { get; set; }


    public override int SaveChanges()
    {
        foreach( var entry in ChangeTracker.Entries())
        {

            var entity = entry.Entity;
            if (entry.State == EntityState.Deleted)
            {
                entry.State = EntityState.Modified; 
                entity.GetType().GetProperty("status").SetValue(entity, '0');
            }
        }
        return base.SaveChanges();

    }
}

}

员工 命名空间 empAPI.Models { 公共课员工 {

    public Guid Id { get; set; }
     public char status{ get; set; } = '1';

    public string Name { get; set; }

    public string Department { get; set; }

  public DateTime?  CreatedDate { get; set; } = DateTime.Now;

} }

【问题讨论】:

    标签: c# asp.net-mvc entity-framework


    【解决方案1】:

    将您的代码更改为:

    public IActionResult Index()
    {
        var employees = _dbContext.Employees.Where(x => x.status == '1').ToList();
        return View(employees);
    }
    

    阅读以下文章:Understanding Action Results

    控制器动作返回称为动作结果的东西。一个 动作结果是控制器动作响应于 浏览器请求。

    ASP.NET MVC 框架支持多种类型的动作结果 包含:

    • ViewResult - 代表 HTML 和标记。
    • EmptyResult - 表示没有结果。
    • RedirectResult - 表示重定向到新的 URL。
    • JsonResult - 表示可在 AJAX 应用程序中使用的 JavaScript 对象表示法结果。
    • JavaScriptResult - 表示 JavaScript 脚本。
    • ContentResult - 表示文本结果。
    • FileContentResult - 表示可下载文件(具有二进制内容)。
    • FilePathResult - 表示可下载文件(带有路径)。
    • FileStreamResult - 表示可下载文件(带有文件流)。

    所有这些操作结果都继承自 ActionResult 基类。

    在大多数情况下,控制器操作会返回一个 ViewResult。

    【讨论】:

    • 还需要注意的是,用户可能想要 return PartialView(employees),或者只是 json,比如 return Ok(employees)
    猜你喜欢
    • 2015-10-24
    • 1970-01-01
    • 2019-02-08
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多