我对存储库模式仍然有些困惑。我想要使用此模式的主要原因是避免从域中调用 EF 4.1 特定的数据访问操作。我宁愿从 IRepository 接口(interface)调用通用的 CRUD 操作。这将使测试更容易,如果我将来必须更改数据访问框架,我将能够这样做而无需重构大量代码。
这是我的情况的一个例子:
我在数据库中有 3 个表:Group
、Person
和 GroupPersonMap
。 GroupPersonMap
是一个链接表,仅由 Group
和 Person
主键组成。我使用 VS 2010 设计器创建了 3 个表的 EF 模型。 EF 非常聪明,可以假定 GroupPersonMap
是一个链接表,因此它不会在设计器中显示。我想使用我现有的域对象而不是 EF 生成的类,因此我关闭了模型的代码生成。
我现有的匹配EF模型的类如下:
public class Group
{
public int GroupId { get; set; }
public string Name { get; set; }
public virtual ICollection<Person> People { get; set; }
}
public class Person
{
public int PersonId {get; set; }
public string FirstName { get; set; }
public virtual ICollection<Group> Groups { get; set; }
}
我有一个像这样的通用存储库接口(interface):
public interface IRepository<T> where T: class
{
IQueryable<T> GetAll();
T Add(T entity);
T Update(T entity);
void Delete(T entity);
void Save()
}
和一个通用的 EF 存储库:
public class EF4Repository<T> : IRepository<T> where T: class
{
public DbContext Context { get; private set; }
private DbSet<T> _dbSet;
public EF4Repository(string connectionString)
{
Context = new DbContext(connectionString);
_dbSet = Context.Set<T>();
}
public EF4Repository(DbContext context)
{
Context = context;
_dbSet = Context.Set<T>();
}
public IQueryable<T> GetAll()
{
// code
}
public T Insert(T entity)
{
// code
}
public T Update(T entity)
{
Context.Entry(entity).State = System.Data.EntityState.Modified;
Context.SaveChanges();
}
public void Delete(T entity)
{
// code
}
public void Save()
{
// code
}
}
现在假设我只想将现有的 Group
映射到现有的 Person
。我必须执行以下操作:
EFRepository<Group> groupRepository = new EFRepository<Group>("name=connString");
EFRepository<Person> personRepository = new EFRepository<Person>("name=connString");
var group = groupRepository.GetAll().Where(g => g.GroupId == 5).First();
var person = personRepository.GetAll().Where(p => p.PersonId == 2).First();
group.People.Add(person);
groupRepository.Update(group);
但这不起作用,因为 EF 认为 Person
是新的,并且会尝试将 Person
重新INSERT
到数据库中会导致主键约束错误。我必须使用 DbSet
的 Attach
方法告诉 EF Person
已经存在于数据库中,所以只需在 Group 之间创建一个映射
和 Person
在 GroupPersonMap
表中。
因此,为了将 Person
附加到上下文,我现在必须向我的 IRepository 添加一个 Attach
方法:
public interface IRepository<T> where T: class
{
// existing methods
T Attach(T entity);
}
修复主键约束错误:
EFRepository<Group> groupRepository = new EFRepository<Group>("name=connString");
EFRepository<Person> personRepository = new EFRepository<Person>(groupRepository.Context);
var group = groupRepository.GetAll().Where(g => g.GroupId == 5).First();
var person = personRepository.GetAll().Where(p => p.PersonId == 2).First();
personRepository.Attach(person);
group.People.Add(person);
groupRepository.Update(group);
已修复。现在我必须处理另一个问题,即每次创建组/人员映射时 Group
都会在数据库中更新。这是因为在我的 EFRepository.Update()
方法中,实体状态明确设置为 Modified'。我必须将组的状态设置为
Unchanged,这样
Group` 表就不会被修改。
要解决此问题,我必须向我的 IRepository 添加某种 Update
重载,它不会更新根实体或 Group
,在这种情况下:
public interface IRepository<T> where T: class
{
// existing methods
T Update(T entity, bool updateRootEntity);
}
Update 方法的 EF4 实现看起来像这样:
T Update(T entity, bool updateRootEntity)
{
if (updateRootEntity)
Context.Entry(entity).State = System.Data.EntityState.Modified;
else
Context.Entry(entity).State = System.Data.EntityState.Unchanged;
Context.SaveChanges();
}
我的问题是:我的处理方式是否正确?当我开始使用 EF 和存储库模式时,我的存储库开始看起来以 EF 为中心。感谢阅读这篇长文
最佳答案
The primary reason why I want to use this pattern is to avoid calling EF 4.1 specific data access operations from the domain. I'd rather call generic CRUD operations from a IRepository interface. This will make testing easier
没有 will not make your testing easier . You exposed IQueryable
所以你的存储库 is not unit testable .
if I ever have to change the data access framework in the future, I will be able to do so without refactoring a lot of code.
不,无论如何你都必须更改大量代码,因为你暴露了 IQueryable
并且因为 EF/ORM 是泄漏抽象 - 你的上层期望一些行为在你的 ORM 中神奇地发生(例如延迟加载).这也是选择存储库的最奇怪的原因之一。现在只需选择正确的技术并使用它来获得它的赌注。如果您以后必须更改它,则意味着 you did a mistake and chose the wrong one or requirements have changed - 无论哪种情况,都需要大量工作。
But this doesn't work because EF thinks Person is new, and will try to re-INSERT the Person into the database which will cause a primary key constraint error.
是的,因为您正在为每个存储库使用新的上下文 = 这是错误的方法。存储库必须共享上下文。您的第二个解决方案也不正确,因为您将 EF 依赖项放回了应用程序 - 存储库公开了上下文。这通常通过第二种模式——工作单元来解决。 Unit of work wraps the context和工作单元形成原子更改集 - SaveChanges
必须在工作单元上公开以提交所有相关存储库完成的更改。
Now I have an issue with the Group being UPDATE'd in the database every time I want to create a Group/Person map.
为什么要改变状态?您从存储库中收到实体,因此在您分离它之前没有理由调用 Attach
并手动更改状态。这一切都应该在附加实体上自动发生。只需调用 SaveChanges
。如果您使用的是分离实体,则 you must correctly set state for every entity和关系,所以在这种情况下,您确实需要一些逻辑或更新重载来处理所有情况。
Am I approaching this the right way? My Repository is starting to look EF centric as I start to work with EF and the repository pattern.
我不这么认为。首先,您没有使用聚合根。如果这样做,您会立即发现 generic repository不适合那个。聚合根的存储库对每个聚合根都有特定的方法来处理由根聚合的关系。 Group
不是 Person
聚合的一部分,但 GroupPersonMap
应该是这样你的 Person 存储库应该有特定的方法来处理从 person 添加和删除组(但是不要自己创建或删除组)。 Imo 通用存储库是 redundant layer .
关于c# - Entity Framework 4.1 和父/子关系的存储库模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7171023/