在MVC 5中使用EF选择特定的列

Jab*_*ria 2 c# asp.net-mvc entity-framework asp.net-mvc-5

我想Entity Framework在MVC 5中使用一些特定的列值。但是它向我显示错误。这是我的控制器方法代码:

public ActionResult Index()
{
    var systemUsers = db.SystemUsers
                        .Include(s => s.SystemUser1)
                        .Select(s => new {
                                          s.FullName, 
                                          s.Email, 
                                          s.Image, 
                                          s.UpdateDate, 
                                          s.UpdatedBy, 
                                          s.Id
                                 });
    return View(systemUsers.ToList());
}
Run Code Online (Sandbox Code Playgroud)

这是错误消息:

传递到字典中的模型项的类型为“ System.Collections.Generic.List 1[<>f__AnonymousType16 [System.String,System.String,System.String,System.Nullable 1[System.DateTime],System.Nullable1 [System.Int32],System.Int32]]”,但是此字典需要类型为'System.Collections.Generic.IEnumerable'1 [MVC.Models.SystemUser]'的模型项。

同样,当我无法获得特定列的单个结果时。默认情况下,控制器方法在尝试使用时也会返回意外的外键数据ajax。这是单个结果的代码。

[HttpPost]
public ActionResult Details(int? id)
{
    if (id == null)
    {
       return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    SystemUser systemUser = db.SystemUsers.Find(id);
    return Json(systemUser);
}
Run Code Online (Sandbox Code Playgroud)

这是控制台中的结果

Nko*_*osi 5

该视图需要强类型视图模型,但是您正在传递匿名类型

更新选择以返回强类型对象集合。

public ActionResult Index()
{
    var systemUsers = db.SystemUsers
                        .Include(s => s.SystemUser1)
                        .Select(s => new SystemUser { //<--HERE
                                         FullName = s.FullName, 
                                         Email = s.Email, 
                                         Image = s.Image, 
                                         UpdateDate = s.UpdateDate, 
                                         UpdatedBy = s.UpdatedBy, 
                                         Id = s.Id
                                 });
    return View(systemUsers.ToList());
}
Run Code Online (Sandbox Code Playgroud)