在内存中创建POCO之后,我在存储库对象上调用Save方法。然后我需要使用在保存操作期间创建的数据库ID更新POCO。我是否应该使用ref传递对象,只需让save方法返回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);
答案 0 :(得分:2)
存储库应保存您的POCO,只需在gc.Id
方法中填写Save
,方法是在保留对象后查询Id
,并且调用方法会看到。{/ p>
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);
int Id = gc.Id; // Save populate the Id