jpshook
jpshook

Reputation: 4944

How should the repository pattern update the ID of the object after a save to database method?

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);

Upvotes: 2

Views: 1896

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

Repository should save your POCO so simply fill gc.Id in the Save method by querying the Id after persisting the object and calling method will see that.

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

Upvotes: 2

Related Questions