gigi
gigi

Reputation: 3946

How to insert in two related tables within the same context( how to retrieve the identity value before SaveChanges )?

Header:
Id => identity, primary key 
...other columns...

Detail:
Id => identity, primary key
HeaderId => foreign key
...other columns...       

public bool CreateHeader(Header header, IEnumerable<Detail> details)
{
    using (TransactionScope tran = new TransactionScope())
    using (TemplateEntities ctx = new TemplateEntities())
    {
        try
        {
            HeaderRepository ihRep = new HeaderRepository(ctx);
            DetailRepository idRep = new DetailRepository(ctx);
            ihRep.Add(header);
            // header.Id is still 0
            foreach (Detail detail in details)
            {
                detail.HeaderId = header.Id;
                idRep.Add(detail);
            }
            ctx.SaveChanges();
            tran.Complete();
            return true;
        }
        catch
        {
            return false;
        }
    }
}

Upvotes: 1

Views: 189

Answers (1)

scmccart
scmccart

Reputation: 1169

Have you tried using the Navigation property rather than the FK Property?

Try switching the body of your foreach to just:

detail.Header = header;

This should inform EF of the relationship and it should manage it from there IIRC. If your idRep.Add performs any other work I'd recommend pulling it out to another method that you can call without it trying to add the detail to the EF context.

Upvotes: 1

Related Questions