如何使用LINQ to Entities的视图模型

时间:2014-11-21 17:59:55

标签: asp.net-mvc entity-framework view model linq-to-entities

我是ASP.NET MVC的新手,但我似乎无法理解有关View Models的规则。我在这里展示的例子绝对类似于各种来源的其他例子,所以我完全不知所措。

我在VS 2013 MVC 5上使用了Code First With Entity Framework 6,并创建了以下两个模型。

    public class Task
    {
        public int TaskId { get; set; }
        public int UserId { get; set; }
        public String Title { get; set; }
        public String Description { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }

        public virtual User User { get; set; }

    }



    public class User
    {
        public int UserId { get; set; }
        public String UserName { get; set; }
        public String Password { get; set; }
        public String FullName { get; set; }
        public String Email { get; set; }
        public String Status { get; set; }
        public String Role { get; set; }
        public virtual ICollection<Task> Tasks { get; set; }

    }

这是我的背景。

public class FRESHContext : DbContext
    {


        public DbSet<User> Users { get; set; }
        public DbSet<Task> Tasks { get; set; }
        public DbSet<Artefact> Artefacts { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }

        public System.Data.Entity.DbSet<FRESH.ViewModel.ManageTasksViewModel> ManageTasksViewModels { get; set; }

    }

现在看到用户和任务之间存在一对多的关系,我想列出任务,显示哪个用户已分配给他们(这个&#39;只是一个学习的例子),所以我认为这将受益于设计一个特殊的视图模型以强烈地键入到View页面并使用LINQ to Entities查询来派生模型以发送到View页面。这是我的视图模型,用于强类型的视图页面。

&#13;
&#13;
  public class ManageTasksViewModel
    {

        public int TaskId { get; set; }
        public int UserId { get; set; }
        public String FullName { get; set; }
        public String Title { get; set; }
        public String Description { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    
    }
&#13;
&#13;
&#13;

不用担心,我正确地强烈键入了View Page,如下所示;

&#13;
&#13;
@model IEnumerable<FRESH.ViewModel.ManageTasksViewModel>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.UserId)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FullName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Title)
        </th>
        <th>

etc etc .............(with brevity in mind lol.)
&#13;
&#13;
&#13;

所以现在我创建了一个LINQ to Entities查询,看了之后对我来说似乎很合理哦,我不知道一千个视频,哈哈。

&#13;
&#13;
 public class ManageTasksController : Controller
    {
        private FRESHContext db = new FRESHContext();

        // GET: ManageTasks
        public ActionResult Index()
        {
          
           var query = (from U in db.Users
                        join T in db.Tasks on U.UserId equals T.UserId
                        select new ManageTasksViewModel
                        {
                            TaskId = T.TaskId,
                            UserId = U.UserId,
                            FullName = U.FullName,
                            Title = T.Title,
                            Description = T.Title,
                            StartDate = T.StartDate,
                            EndDate = T.EndDate

                        }).Take(10).ToList();
            
            
            
            return View("Index",query);
        }
&#13;
&#13;
&#13;

当然它已经建成了! yeehaar!,但是当代码到达ActionResult Index()时,我得到了这个例外。

&#13;
&#13;
An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: The entity or complex type 'FRESH.DAL.ManageTasksViewModel' cannot be constructed in a LINQ to Entities query.
&#13;
&#13;
&#13;

所以我做错了什么,而且我可以用另一种方式做得更好,我还没有看过LINQ to SQL,因为我认为这种方法肯定会起作用。任何帮助将非常感激。谢谢。

2 个答案:

答案 0 :(得分:2)

您的dbcontext中不应该有viewmodel。这只是一个viewModel,与您的实体完全不同。

public System.Data.Entity.DbSet<FRESH.ViewModel.ManageTasksViewModel> 
      ManageTasksViewModels { get; set; }

答案 1 :(得分:0)

感谢所有那些花时间帮助我的人,基本上我再次阅读Contoso大学的教程并得到了答案,基本上它与我的第一次尝试非常类似,除了我正在努力。

选择新的ManageTasksViewModel            {               。               。               。            };

而我应该说;

选择新的ManageTasksViewModel()            {               。               。               。            }

    public class ManageTasksController : Controller
    {
        private FRESHContext db = new FRESHContext();

        // GET: ManageTasks
        public ActionResult Index()
        {

            IQueryable<ManageTasksViewModel> query = from tasks in db.Tasks
                                                     join users in db.Users on tasks.UserId equals users.UserId
                                                     select new ManageTasksViewModel()
                                                   {
                                                       TaskId = tasks.TaskId,
                                                       UserId = users.UserId,
                                                       FullName = users.FullName,
                                                       Title = tasks.Title,
                                                       Description = tasks.Description,
                                                       StartDate = tasks.StartDate,
                                                       EndDate = tasks.EndDate
                                                   };
            return View(query.ToList());
        }

无论如何希望这对某人有用。