c# - How to access navigation properties in EF using repository pattern -
context: asp.net web application
the base repository (abstract class) implements needed base functionality other repositories inherit: i.e. -personrepo -addressrepo
edit: place code queries several db tables , of them not directly related navigation property in respective repository?
now, best way access navigation properties? cumbersome when using repository pattern. if there not convenient solution this, stick old dal layer inside , work dbcontext directly.
i came temporary solution accessing navigation properties in personrepository implementation:
public person insertnewpersonwithaddress(person p, address addr) { this.insert(p); // insert person var ar = new addressrepository(this.ctx); ar.insert(addr); // insert address this.addresses(p).add(addr); // add address person return p; } /* navigation properties */ icollection<address> addresses(person p) { return ctx.entry<person>(p).collection<address>("addresses").currentvalue; }
base repository class implements following interface
public interface irepository<t> t : class { iqueryable<t> all(); iqueryable<t> findby(expression<func<t, bool>> predicate); t insert(t entity); ienumerable<t> insertmultiple(ienumerable<t> items); t delete(t entity); ienumerable<t> deletemultiple(ienumerable<t> items); t update(t entity); ienumerable<t> updatemultiple(ienumerable<t> items); void save(); }
db-design:
person --> personaddress(junction table) <-- address
any intelligent solution problem?
you thinking wrong way. navigation property property of entity, not property of repository. don't need instantiate repository navigation property, can added directly entity.
public person insertnewpersonwithaddress(person p, address addr) { p.address = addr; this.insert(p); // insert person return p; }
now, if inserting new person
want attached existing address
(rather inserting new copy of both), can expose addressid
fk property on person
entity, , pass in fk
value link. in either case, it's not necessary repository need access other.
Comments
Post a Comment