How to make this Model in ASP.NET MVC3?

2019-06-03 00:49发布

问题:

I'm quite new to ASP.NET MVC in fact this is my first ever project using it. I want to build simple TaskList. I'm fairly fine in ASP.NET but know almost nothing about ASP.NET MVC or Linq so please keep this in mind while answering.

I'm using CodeFirst Entity Frameword to generate Db.

I have two tables Users(id,name) and Tasks(id,userid,name). I have created two Model objects which hold Users and Tasks properties. So instead of having int userID as database design would suggest i have an User class inside of Task class to connect Task to certain User.

Somehow i've managed to create join using LINQ

   var model = from t in _db.Tasks
                join u in _db.Users on t.User.ID equals u.ID
                select new { UserID = u.ID,UserName = u.Name,t.Name,t.ID };
    return View(model);

but i cannot bind it to a view, i binded it to Task Model which probably cause this error.

How do i solve this issue, maybe there is some kind of ViewModel i need to create or something like that?

Thanks...

回答1:

You should create a ViewModel and pass it to your view:

public class TaskViewModel
{
    public int TaskId { get; set; }
    public string TaskName { get; set; }
    public int UserId { get; set; }
    public int Username { get; set; }
}

Than create a strongly typed view:

@model IEnumerable<YourNamespace.Models.TaskViewModel>
//Display model data

And Linq query:

var model = from t in _db.Tasks
            join u in _db.Users on t.User.ID equals u.ID
            select new TaskViewModel
            {
                TaskId = t.ID,                    
                TaskName = t.Name,
                UserId = u.ID,
                Username = u.Name
            };


回答2:

Your Linq query uses what's called deferred execution. Meaning that the query itself holds no records and you have to do something with it to make it execute.

So try this:

return View(model.ToList());