【发布时间】:2015-06-05 11:13:51
【问题描述】:
上下文:ASP.NET Web 应用程序
Base Repository(抽象类)实现了所有其他存储库继承所需的基本功能: IE。 -PersonRepo -AddressRepo
编辑: 您将查询多个数据库表的代码放在哪里,其中一些与相应存储库中的导航属性没有直接关系?
现在,访问导航属性的最佳方式是什么? 使用存储库模式时非常麻烦。 如果没有方便的解决方案,我会坚持使用旧的 DAL 层,里面包含所有内容,并直接使用 DbContext。
我刚刚想出了一个在我的 PersonRepository 实现中访问导航属性的临时解决方案:
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 to person
return p;
}
/* Navigation Properties */
ICollection<Address> Addresses(Person p)
{
return ctx.Entry<Person>(p).Collection<Address>("Addresses").CurrentValue;
}
Base Repository类实现如下接口
public interface IRepository<T> where 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();
}
数据库设计:
Person --> PersonAddress(联结表)
这个问题有什么智能解决方案吗?
【问题讨论】:
-
在 EF 中使用存储库模式有什么好处?阅读thereformedprogrammer.net/…。
标签: c# entity-framework repository-pattern