存储库模式与实体框架4.1和父/子关系
我仍然有一些与存储库模式混淆。我想要使用这种模式的主要原因是为了避免从域中调用EF 4.1特定的数据访问操作。我宁愿从IRepository接口调用通用的CRUD操作。这将使测试变得更容易,如果将来我必须更改数据访问框架,我将能够在不重构大量代码的情况下进行测试。存储库模式与实体框架4.1和父/子关系
这里是我的情况为例:
我在数据库中有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; }
}
我有一个通用的存储库接口,像这样:
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
是新的,并会尝试重新INSERT
的Person
到数据库中,这将导致一个主键约束错误。我必须使用DbSet
的Attach
方法来告诉EF Person
已经存在于数据库中,因此只需在GroupPersonMap
表中创建Group
和Person
之间的映射。
因此,为了连接Person
的方面,我现在必须的Attach
方法添加到我的IRepository:
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'. I must set the Group's state to
未更改so the
组表未被修改。
为了解决这个问题,我必须添加某种Update
过载到我的IRepository不更新根实体,或Group
的,在这种情况下:
public interface IRepository<T> where T: class
{
// existing methods
T Update(T entity, bool updateRootEntity);
}
更新方法的EF4 implentation看起来会是像这样:
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和存储库模式时,My Repository开始看起来以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存储库应该具有特定的方法来处理从人员添加和删除组(但不创建或删除组本身)。 Imo通用存储库是redundant layer。
+1很好的答案 –
+1非常丰富的 –
+1为实体框架+工作单元。存储库需要共享相同的dbcontext。我敢打赌,这是我的问题。 – Jhayes2118