LINQ to Entities 查询中的 Include()
我的 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; }
}
作为参考,这里是我的 DbContext 类:
public class TaskManagerSets : DbContext
{
public DbSet<Task> TaskSet { get; set; }
public DbSet<TaskStatus> TaskStatusSet { get; set; }
}
然后我的 TaskController< 中有一个 List 操作/strong>:
TaskManagerSets dbcontext = new TaskManagerSets();
public ActionResult List()
{
var tasks = from tsk in dbcontext.TaskSet.Include("TaskStatusSet")
select tsk;
return View(tasks.ToList());
}
最后我有了任务列表视图:
@model IEnumerable<TaskManager.Models.Task>
<ul>
@foreach (var tsk in Model)
{
<li>@tsk.Id | @tsk.CreatedOn | @tsk.Status.Description</li>
}
</ul>
当我执行我的项目时,出现以下错误:
指定的包含路径无效。 EntityType“CodeFirstNamespace.Task”未声明名称为“TaskStatus”的导航属性。
问题肯定出在 Include("TaskStatusSet")
上,但我应该如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您正在使用
DbContext
API,因此最好的选择是使用 Include 的类型安全重载:使用 System.Data.Entity;
您将获得智能感知和编译时检查,这有助于避免像您一样出现错误字符串的问题。
不太令人满意的非类型安全技术是:
注意:技术的呈现顺序已更改,因此在阅读评论时请记住这一点。
Since you are working with the
DbContext
API the best option is to use the type-safe overload of Include:using System.Data.Entity;
You will get Intellisense and compile-time checks which helps to avoid issues with wrong strings like you had.
The less satisfactory, NON-type-safe technique would be:
Note: the presented order of the techniques has been changed, so keep this in mind when reading comments.