我正在阅读存储库的用法。有时我看到存储库是实体的属性。我想知道优缺点是什么。
public interface IRepository<T>
{
T GetById(int id);
void Update(T);
}
public class FooRepository : IRepository<Foo>
{
public Foo GetById(int i)
{ /* code ..*/ }
void Update(Foo)
{ /*code..*/ }
}
public class Foo
{
public IRepository Repository {get;set;}
public void Update()
{
Repository.Update(this);
}
}
为什么要使用这个方法?将存储库和实体对象分开使用不是更有意义吗?这样实体对象就不知道任何存储库了?
编辑:
但是如果你有一个主对象和不同的子对象怎么办:
public class MainObject
{
public int Id {get;set;}
public List<ISubject> SubObjects {get;}
}
public interface ISubObject
{
}
public class SubObjectA : ISubObject
{
public string SomeProperty {get;set;}
public int Id {get;set;}
public int MainObjectId {get;set;}
}
public class SubObjectB : ISubObject
{
public string AnotherProperty{get;set;}
public int Id {get;set;}
public int MainObjectId {get;set;}
}
所以 SubObjectA 和 SubObjectB 是不同的类型但是实现了 ISubject 接口(interface)。主对象有这些子对象的列表。每个子对象都有自己的存储库。您将如何加载子对象?
最佳答案
一些实体实现需要访问创建它们的上下文,例如实现延迟加载。请考虑以下事项:
class MyEntity
{
public virtual IEnumerable<string> Tags { get; private set; }
}
interface IMyEntityRepository
{
...
}
您可以从 MyEntity 实现返回 MyEntity 的子类,这需要对创建它的存储库的引用。
internal class MyLazyEntity : MyEntity
{
public MyLazyEntity(MyLazyEntityRepository repository)
{
this.Repository = repository;
}
public override IEnumerable<string> Tags
{
get
{
return this.Repository.LoadTagsForEntityFromXml(this.Id);
}
}
}
class MyLazyEntityRepository : IMyEntityRepository { }
我会说,在从实体派生的类中保留对源存储库的引用很好,另一方面,基本实体类不应该知道存储库。
关于C# 为什么使用存储库作为属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5115455/