Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4 load and include combine

If I have 3 tables:

Table1, Table2, Table3

And Table3 has a FK for Table2, which has a FK to Table1

Then I load my object like this:

using(Entities entities = new Entities()
{
     Table1 table = entities.Table1.FirstOrDefault();
     table.Table2.Load();
}

How can I eagerly load table3 to table2 because LazyLoading is switched off.

I know I can use Include in the FirstOrDefault statement, but it will generate a much too big join.

ANSWER

using(Entities entities = new Entities())
{
    Table1 table = entities.Table1.FirstOrDefault();
    var table2 = table.Table2.CreateSourceQuery().Include("Table3")
        .Execute(MergeOption.AppendOnly);
    table.Table2.Attach(table2);
}
like image 407
Roger Far Avatar asked Jun 21 '26 08:06

Roger Far


1 Answers

How can I eagerly load table3 to table2 because LazyLoading is switched off.

You can try:

using(Entities entities = new Entities())
{
    Table1 table = entities.Table1.FirstOrDefault();
    table.Table2.CreateSourceQuery().Include("Table3")
        .Execute(MergeOption.AppendOnly);
}

I assume that you are using entities derived from EntityObject, not POCOs, i.e. table.Table2 is an EntityCollection<T> or EntityReference<T>. I am not 100% sure if the above code will work as expected.

like image 151
Slauma Avatar answered Jun 22 '26 23:06

Slauma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!