[英]Include() in LINQ to Entities query
I have the following models in my ASP.NET MVC 3 project: 我的ASP.NET MVC 3项目中有以下模型:
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: 作为参考,这是我的DbContext类:
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 : 然后我在TaskController中有一个List Action:
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'. EntityType'CodeFirstNamespace.Task'不声明名为'TaskStatus'的导航属性。
The problem is definitely on the Include("TaskStatusSet")
but how should I fix this? 问题肯定在Include("TaskStatusSet")
但我该如何解决这个问题呢?
The navigation property name in your Task
class is Status
. Task
类中的导航属性名称是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: 但是,由于您正在使用DbContext
API,更好的选择是使用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. 您将获得Intellisense和编译时检查,这有助于避免出现像您一样的错误字符串问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.