c# - How can I generically .Include properties of entities limited to a certain class? -
i using entity framework 6.x t4 templates generate both dbcontext , entity classes .edmx. of entities inherit class called baseentity. take example following sample entity:
public partial class userentity : baseentity { [identitycolumn] public int id { get; set; } public string name { get; set; } public int fkuserlocationid { get; set; } [navigationcolumn] public virtual icollection<userrole> userroles { get; set; } [navigationcolumn] public virtual userlocation userlocation { get; set; } } userrole , userlocation inherit baseentity. have generic repository interface igenericrepository<tentity> tentity : baseentity , implementation of genericrepository<tentity> tentity: baseentity:
public class genericrepository<tentity> : igenericrepository<tentity> tentity : baseentity { protected readonly mydbcontext _context; protected readonly dbset<t> _dbset; public genericrepository(mydbcontext context) { _context = context; _dbset = context.set<t>(); } //would limit object of type baseentity or icollection<baseentity> public iqueryable<tentity> get(params expression<func<tentity, object>>[] includeproperties) { var query = _dbset.asqueryable(); foreach (var include in includeproperties){ query = query.include(include); } return query; } } with of that, able include entities doing like:
//assume repository exists _userrepository.get(user => user.userroles, user => user.userlocation); //valid include _userrepository.get(user => user.name); //invalid include appears in intellisense how can correctly define method that baseentity properties (or properties navigationcolumn attribute) valid in func?
public class genericrepository<tentity> : igenericrepository<tentity> tentity : baseentity { protected readonly mydbcontext _context; protected readonly dbset<t> _dbset; public genericrepository(mydbcontext context) { _context = context; _dbset = context.set<t>(); } //would limit object of type baseentity or icollection<baseentity> public iqueryable<tentity> get(params expression<func<tentity, object>>[] includeproperties) { var query = _dbset.asqueryable(); //something may help? wont solve issue of intelisense knowing allowed , not allowed. includeproperties = includeproperties.where(p=>p.type.declaringtype.getcustomattributes(typeof(navigationproperty),true).any()); foreach (var include in includeproperties){ query = query.include(include); } return query; } }
Comments
Post a Comment