开发者

Entity Framework - Querying Inheritance

开发者 https://www.devze.com 2023-01-28 10:38 出处:网络
I was tasked as a homework assignment to make a task tracker. I wanted to learn entity framework for this assignment, especially how to use the inheritance aspects. Projects, tasks and sub-tasks all h

I was tasked as a homework assignment to make a task tracker. I wanted to learn entity framework for this assignment, especially how to use the inheritance aspects. Projects, tasks and sub-tasks all have a lot of similar properties, so I thought I would use inheritance, but can't figure out how to query particular projects.

I drew this diagram in Visual Studio:

Entity Framework - Querying Inheritance

I then created the database from this model. How can I get an Employees Projects?

I've started with this:

ModelContainer m = new ModelContainer()开发者_JAVA百科;
var employee = (from e in m.Employees 
               where e.UserName == username
               select e).First<Employee>();

But ((Employee)employee).Projects is not available, but ((Employee)employee).Items is. ((Employee)employee).Items.Projects is also not available. How do I get an Employee's projects? Should I add a Navigation Property to Employees for this?


You'll have to use the Queryable.OfType(TResult) extension method in order to filter the entities of type Manager:

using (var model = new ModelContainer())
{
    Manager manager = (from m in model.Employees.OfType<Manager>()
                       where m.UserName == username
                       select m).FirstOrDefault();
}

Related resources:

  • Inheritance and Associations with Entity Framework Part 3
  • Lerman, Julia, Programming Entity Framework, O'Reilly 2010
0

精彩评论

暂无评论...
验证码 换一张
取 消