在保存到数据库方法之后,存储库模式应该如何更新对象的ID
本文关键字:何更新 更新 ID 对象 方法 数据库 保存 之后 模式 存储 | 更新日期: 2023-09-27 17:57:33
在内存中创建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);
Repository应该保存您的POCO,所以只需在持久化对象后通过查询Id
在Save
方法中填充gc.Id
,调用方法就会看到这一点。
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