c# - LINQ to Entities 查询中的 Include()

标签 c# .net asp.net-mvc-3 entity-framework-4 linq-to-entities

我的 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 操作:

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

我终于有了任务 ListView :

 @model IEnumerable<TaskManager.Models.Task>

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

当我执行我的项目时,出现以下错误:

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

问题肯定出在 Include("TaskStatusSet") 上,但我应该如何解决这个问题?

最佳答案

Task 类中的导航属性名称是 Status。所以,你必须使用:

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

但由于您正在使用 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;

您将获得 Intellisense 和编译时检查,这有助于避免像您一样出现错误字符串的问题。

关于c# - LINQ to Entities 查询中的 Include(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5648154/

相关文章:

c# - 在 TFS 2012 上构建 c#6.0

.net - 如何让企业库配置和项目设置设计器在app.config中引用相同的值

.net - 使用 Lutz 反射器查看 IL 代码

.net - .NET 4.6.1 中的默认 ServicePointManager.SecurityProtocol 值是什么?

twitter-bootstrap - hidden-xs 在 Bootstrap 中打印时隐藏 div

c# - "not in"的 Lambda 表达式?

c# - 对 IEnumerable 的更改不会在查询之间保留

c# - asp.net mvc 3 View 中 foreach 循环中每个元素的唯一 ID?

asp.net-mvc-3 - ASP.NET MVC 3 预编译

c# - 在 C# 中将大字符串作为返回值传递有多慢?