在内存中创建我的 POCO 后,我调用存储库对象的 Save 方法。然后我需要使用保存操作期间创建的数据库 ID 更新 POCO。我应该使用 ref 传递对象,简单地让保存方法返回 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
将 gc.Id
填入 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);
int Id = gc.Id; // Save populate the Id
关于c# - 在保存到数据库方法之后,存储库模式应该如何更新对象的 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6102717/