2015-01-12 74 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'地址。導航屬性還有其他方法嗎? –