c# - 在保存到数据库方法之后,存储库模式应该如何更新对象的 ID?

标签 c# asp.net repository-pattern

在内存中创建我的 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,因此只需在保存对象和调用方法后通过查询 Idgc.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/

相关文章:

c# - 无法从 Gridview 获取值

sql - 三层架构与存储库模式

c# - 在连续大写字母序列的最后一个之前添加一个空格的正则表达式

c# - 来自 C# 的 Windows 模拟

c# - 在 ASP.NET 5 中从 config.json 中检索部分

repository - 领域驱动设计中的规范模式

java - 存储库模式 - 如何理解它以及它如何与 "complex"实体一起使用?

c# - 从c#中的double中提取尾数和指数

c# - autogeneratecolumns=true 时如何实现 wrap 属性?

asp.net - 间歇性 'the remote name could not be resolved'?