2
在內存中創建我的POCO後,我調用存儲庫對象上的Save方法。然後我需要使用保存操作期間創建的數據庫ID來更新POCO。我是否應該使用ref傳遞對象,只需使用save方法返回ID並手動更新調用頁面中的對象,或者什麼?保存到數據庫方法後,存儲庫模式應該如何更新對象的ID?
下面是一些示例代碼:
public GiftCertificateModel
{
public int GiftCerticiateId {get;set;}
public string Code {get;set;}
public decimal Amount {get;set;}
public DateTime ExpirationDate {get;set;}
public bool IsValid()
{}
}
public GiftCertificateRepository
{
public GiftCertificateModel GetById(int GiftCertificateId)
{
//call db to get one and return single model
}
public List<GiftCertificateModel> GetMany()
{
//call db to get many and return list
}
public string GetNewUniqueCode()
{
//randomly generates unique code
return code;
}
public GiftCertificateModel CreateNew()
{
GiftCertificateModel gc = new GiftCertificateModel();
gc.Code = GetNewUniqueCode();
return gc;
}
//should this take by ref or just return the id or return a full new model?
public void Save(GiftCertificateModel gc)
{
//call db to save
}
}
GiftCertificateRepository gcRepo = new GiftCertificateRepository();
GiftCertificateModel gc = gcRepo.CreateNew();
gc.Amount = 10.00M;
gc.ExpirationDate = DateTime.Today.AddMonths(12);
gc.Notes = "Test GC";
gcRepo.Save(gc);
這就是我所做的。它讓POCO擁有一個可設置ID的「感覺很有趣」,但它看起來效果最好。可能需要爲CreateDate等其他字段執行相同操作。 – n8wrl 2011-05-23 20:45:42
ID的可訪問性取決於POCO定義的圖層(程序集)。如果它在與存儲庫相同的圖層中定義,則可以使ID設置器處於內部,但很可能不想這樣做,因爲它會破壞ASP.NET中用於數據綁定的一些場景。是的,你可以爲其他自動填充的屬性做同樣的事情。 – 2011-05-23 20:47:45
@Ladislav Mrnka - 感謝您的迴應,但您是如何真正從回購中獲取ID的?應該創建的原始gc是在repo中設置的實例嗎? (請在原帖中查看我的示例代碼)很高興看到我至少在正確的軌道上! – jpshook 2011-05-23 20:53:32