简体   繁体   中英

EF6 Get entity with list property from stored procedure

My stored procedure returns a joined table like:

Employee Department
-------------------
John     IT
Bob      IT
Rob      IT
Jane     Sales
Mary     Sales

I have the appropriate entities generated by EF:

class Employee
{
   public int Id {get;set;}
   public string Name{get;set;}
   public int DepartmentId{get;set;}
   public Department Deparment{get;set;}
}

class Department
{
   public int Id {get;set;}
   public string Name{get;set;}
   public ICollection<Employees> Employees{get;set;}
}

I execute the stored procedure like this:

Database.SqlQuery<Department>("exec spGetDepartments").ToList();

And the result is a list of departments:

IT
IT
IT
Sales
Sales

Each has empty list of employees.

Can I have the 2 department entities with lists of corresponding employees?

The example is simplified, but the business requirement is use stored procedure as there is a complicated logic which is hard to replicate in LINQ.

You cannot employ the navigation properties on stored procedures. Note the stored procedure doesn't actually employ a context method call, but an actual query execution.

You have to use the DBcontext, to accomplish the task you require. Stored procedures aren't "composable". The "Lazy loading" or its variants are only available via a context.

You could in theory achieve a read statement in a generic repository pattern, if you absolutely wanted to. It might even be efficient under some circumstances.

But in that case, your resultset on the stored procedure, would always have to hold your entire row set. The behavior would be quite complicated. I wouldn't actually advise it. It might be possible, but smart? decidedly not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM