包括()在LINQ to Entities查询 [英] Include() in LINQ to Entities query

查看:161
本文介绍了包括()在LINQ to Entities查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的ASP.NET MVC 3项目以下型号:

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; }
}

有关参考,这里是我的的DbContext 类:

For reference, here is my DbContext class:

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

然后我有一个列表的行动我的 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:

指定的include路径是无效的。该的EntityType'codeFirstNamespace.Task'没有名为'TaskStatus声明导航属性。

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

问题肯定是在包含(TaskStatusSet)但我应该怎么解决这个问题?

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

推荐答案

任务类导航属性名称是状态。所以,你将不得不使用:

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;

但因为你是用的DbContext API一个更好的选择是使用类型安全的过载工作包括:

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.

这篇关于包括()在LINQ to Entities查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆