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

时间:2016-12-25 17:46:52

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

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

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());
}

这是错误消息:

  

传递到字典中的模型项的类型是&#39; System.Collections.Generic.List 1[<>f__AnonymousType1 6 [System.String,System.String,System.String,System.Nullable {{1} 1 [System.Int32],System.Int32]]&#39;,但是这个字典需要一个类型为&#39; System.Collections.Generic.IEnumerable`1 [MVC.Models.SystemUser]&#39的模型项;

当我无法获得具有特定列的单个结果时。默认情况下,控制器方法在尝试使用1[System.DateTime],System.Nullable时也会返回意外的外键数据。 这是单个结果的代码。

ajax

Here is the result in console

2 个答案:

答案 0 :(得分:4)

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

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

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());
}

答案 1 :(得分:1)

此处的问题似乎是您的View希望IEnumerable<SystemUser>查看模型,而是提供anonymous type实例。这就是编译器失败的原因。有几种方法可以解决这个问题:

1-让您的查看接受dynamic模式:您不必担心传入的实际实例的类型,但是你不会有自动完成 intellisense 的细节。

2-不要预览(.Select)您的收藏集并将原始SystemUser列表传递给查看

3-创建视图模型并列出此类视图模型并将其传递给视图:

控制器:

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

恕我直言,第三是最好的。您当然应该使用最适合您需求的那个。希望这个帮助