c# - Apply Include and ThenInclude based on Lambda Expressions Dictionary -


i have few entity framework 7 (core) entities:

public class person {    public virtual address address { get; set; }    public virtual icollection<hobby> hobbies { get; set; } }  public class address {    public string street { get; set; }    public virtual country country { get; set; } } 

and have string array follows:

string[] entities = new string[] { "hobbies", "address.country" } 

given string array got:

context.persons   .include(x => x.hobbies)   .include(x => x.address).theninclude(x => x.country); 

in ef6 like:

context.persons.include(entities[0]).include(entities[1]); 

but in ef7 include not allow strings. created dictionary:

private readonly dictionary<string, lambdaexpression> _properties = new dictionary<string, lambdaexpression>(); 

which have like:

x => x.hobbies "hobbies" x => x.address.country "address.country"      

and have extension:

public static iqueryable<t> include<t>(this iqueryable<t> source, dictionary<string, lambdaexpression> properties) { } 

where need given dictionary apply following:

  1. for "x => x.hobbies" do:

     source.include(x => x.hobbies); 
  2. if expression "x => x.address.country" add:

     source.include(x => x.address).theninclude(x => x.country); 

can done?

not sure theninclude() , ef 7, can in repositories (tested ef 6):

public myentity getmyentity_eagerlyload(dbcontext context, int id, params expression<func<myentity, object>>[] propertiestoload) {     var q = context.myentities.where(m => m.id == id);      foreach (var prop in propertiestoload)         q = q.include(prop);      return q.singleordefault(); } 

you can call this:

repo.getmyentity_eagerlyload(context, id, m => m.property1, m => m.property2, m => m.property1.nestedproperty) 


edit: there alternative way eager loading ef using projection. generic repository method this:

public myentity getmyentity_eagerlyload<t>(dbcontext context, int id, expression<func<myentity, t>> loadingprojection, func<t, myentity> resultprojection) {     var q = context.myentities.where(m => m.id == id);      return q.select(loadingprojection).asenumerable().select(resultprojection).singleordefault(); } 

and call properties want loaded , entity want method return:

repo.getmyentity_eagerlyload(context, id, m => new { myentity = m, m.property1, m.property2, m.property1.nestedproperty }, m => m.myentity) 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -