Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...