2015-01-12 75 views
0

我对存储库模式的使用相当陌生,而且我正在努力如何在使用存储库的模型中实现关系。因此,例如我有以下两种库接口:IPersonRepositoryIAddressRepository存储库模式和模型关系和依赖注入

public interface IPersonRepository 
{ 
    IList<Person> GetAll(); 
    Person GetById(int id); 
} 

public interface IAddressRepository 
{ 
    IList<Address> GetAll(); 
    Address GetById(int id); 
    Address GetByPerson(Person person); 
} 

和两个模型类:PersonAddress

public class Person 
{ 
    private IAddressRepository _addressRepository; 

    public string FirstName { get; set; } 
    public string LastName { get; set; } 

    private Address _address; 
    public Address Address 
    { 
     get { return _addressRepository.GetByPerson(this); } 
     set { _address = value; } 
    } 

    Person(string firstName, string lastName, IAddressRepository addressRepository) 
    { 
     this.FirstName = firstName; 
     this.LastName = lastName; 
     this._addressRepository = addressRepository; 
    } 
} 

public class Address 
{ 
    public string Street { get; set; } 
    public string City { get; set; } 
    public string Zip { get; set; } 
    public List<Person> Persons { get; set; } 

    Address(string street, string city, string zip) 
    { 
     this.Street = street; 
     this.City = city; 
     this.Zip = zip; 
    } 
} 

所以现在我的问题是:是否有罚款注入的IAddressRepositoryPerson类并通过从实际的Person对象中的获取器中延迟加载请求实际地址?另外,如果它有一个像GetPersons()这样的方法,我会注入IPersonRepositoryAddress对象吗?我这样问是因为我重构了一些代码来使用存储库模式,并希望利用依赖注入来使它在稍后的时间点更好地测试。

此外:我没有使用任何ORM,因为我正在SharePoint环境中开发,我正在使用SharePoint列表作为域模型的实际数据存储。

+2

在对象本身中引用存储库似乎非常奇怪。做这件事的原因是什么? –

+0

嗯,我想我只是不知道如何做得更好。 :)在支持数据存储的延迟加载的同时,如何建立与“Address”的关系? –

+0

你正试图做EF已经为你做的事情。 EF生成代理类以注入额外的代码以用于延迟加载。 检查** [this](http://www.alachisoft.com/resources/articles/entity-framework-poco-lazy-loading.html)**文章,看看它是否有帮助。 – Nilesh

回答

0

如果我自己这样做,我不会将资源库注入到模型中。

取而代之的是,在地址模型中,我会有一个personId字段,或者如果您要跟踪每个地址的多个人,则需要一个personIds集合。

这样做,您可以在地址存储库上有一个名为GetByPersonId(int personId)的方法,然后通过检查该人员的ID是否与地址上的ID匹配或该地址上包含的地址上的ID集合来获取该地址personId传入。

+0

纠正我,如果我得到这个错误,但会使用一种名为'GetByPersonId(int personId)'的方法有什么区别?我仍然需要一些对'Person'对象'Address' getter中'AddressRepository'的引用来接收实际的地址。 –

+0

它不会在人的内部没有。你可以把它放在这个人身上,但是注入到你的实体中的库不是很好,很干净。我自己,无论需要什么,我都会去找一个人,然后当我需要这个地址时,直接使用这个人的ID来调用存储库中的方法。例如,如果您是在MVC控制器中执行此操作,则会将两个存储库注入控制器,并在必要时进行调用。 –

+0

好吧,我得到了这个,但是当我使用存储库手动请求地址时,我可以省略Address属性,并且不会有延迟加载支持'Person'地址。导航属性还有其他方法吗? –