Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

c# - Include() in LINQ to Entities query

I have the following models in my ASP.NET MVC 3 project:

public class Task
{
    public int Id { get; set; }
    public DateTime CreatedOn { get; set; }
    public TaskStatus Status { get; set; }
}

public class TaskStatus
{
    public int Id { get; set; }
    public string Description { get; set; }
}

For reference, here is my DbContext class:

public class TaskManagerSets : DbContext
{
    public DbSet<Task> TaskSet { get; set; }
    public DbSet<TaskStatus> TaskStatusSet { get; set; }
}    

Then I have a List Action in my TaskController:

TaskManagerSets dbcontext = new TaskManagerSets();
public ActionResult List()
{
    var tasks = from tsk in dbcontext.TaskSet.Include("TaskStatusSet")
                select tsk;
    return View(tasks.ToList());
}

Finally I have the Task List View:

 @model IEnumerable<TaskManager.Models.Task>

 <ul>
 @foreach (var tsk in Model) 
 { 
    <li>@tsk.Id | @tsk.CreatedOn | @tsk.Status.Description</li> 
 } 
 </ul>

When I execute my project I get the following error:

A specified Include path is not valid. The EntityType 'CodeFirstNamespace.Task' does not declare a navigation property with the name 'TaskStatus'.

The problem is definitely on the Include("TaskStatusSet") but how should I fix this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The navigation property name in your Task class is Status. So, you would have to use:

var tasks = from tsk in dbcontext.TaskSet.Include("Status")
            select tsk;

But since you are working with the DbContext API a better option is to use the type-safe overload of Include:

using System.Data.Entity;
// You must add a using statement for this namespace to have the following 
// lambda version of Include available

//...

var tasks = from tsk in dbcontext.TaskSet.Include(t => t.Status)
            select tsk;

You will get Intellisense and compile-time checks which helps to avoid issues with wrong strings like you had.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...