loading navigation properties with raw sql query

c# entity-framework-6

Question

This is my SQL query:

SELECT 
    t.ServerId, t.Id, s.Name
FROM 
    MyTable as t
JOIN 
    Server s ON t.ServerId = S.Id

This is what I'm using:

context.Database.SqlQuery<entity>("query_goes_here");

How can I set up EF so it loads theServer an attribute of my entity with the information the query returned?

I ultimately decided to do this in response to @octavioccl's response:

foreach(var result in results)
{
    context.Attach(result);
    context.Entry(result).Reference(p => p.Server).Load();
}

But I'm worried that this is causing several db trips?

1
8
8/17/2015 4:27:15 PM

Accepted Answer

ZZZ_tmp
8
8/17/2015 4:22:23 PM

Popular Answer

You can load your main object once you have loaded all the rows for your navigation property. If you want, apply a filter on it first.

var servers = context.Servers.Where(m => m.ServerType == "Windows").ToList();
var mytable = context.MyTables.ToList();

using SqlQuery, or

var servers = context.Database.SqlQuery<Server>("query_goes_here");

foreach (var serv in servers)
    context.Servers.Attach(serv);

then use a query to MyTable, and EF will connect the two for you.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow