在保存到数据库方法之后,存储库模式应如何更新对象的 ID?
在内存中创建 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);
After I create my POCO in memory, I call the Save method on the repository object. I need to then update the POCO with the database ID created during the save operation. Should I pass the object in using ref, simply have the save method return the ID and manually update the object from the calling page, or what?
Here is some sample code:
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
存储库应该保存您的 POCO,因此只需在保存对象并调用方法后查询
Id
,在Save
方法中填写gc.Id
即可。Repository should save your POCO so simply fill
gc.Id
in theSave
method by querying theId
after persisting the object and calling method will see that.