Write fk shortly after pk is generated with entity

0

I have a system and in this system there are some tables that are associative. As soon as I write to the DB the main table, I need to ensure that the new PK generated is written to three other tables, but you have to ensure that it is generated. The system runs on the web and this needs to be avoided if someone else is using the same routine and fire another PK, right?

Here I generate the PK that will be FK in the other tables

[HttpPost]
public void GravaResponsavel(string _responsavel, bool _ativo)
        { 
            using(RupturaEntities db = new RupturaEntities())
            {
                Responsavel resp = new Responsavel();
                try
                {
                    resp.NM_Responsavel = _responsavel;
                    resp.Ativo = _ativo;
                    db.Responsavel.Add(resp);
                    db.SaveChanges();
                }
                catch(Exception ex)
                {}
            }
        }
    
asked by anonymous 28.08.2014 / 18:34

1 answer

1

At the end of the record, do you get the id of the Responsavel table does not solve the problem?

[HttpPost]
public void GravaResponsavel(string _responsavel, bool _ativo)
{ 
    using(RupturaEntities db = new RupturaEntities())
    {
        Responsavel resp = new Responsavel();
        Tabela1 tbl1 = new Tabela1();
        Tabela2 tbl2 = new Tabela2();
        Tabela3 tbl3 = new Tabela3();
        try
        {
            resp.NM_Responsavel = _responsavel;
            resp.Ativo = _ativo;
            db.Responsavel.Add(resp);
            db.SaveChanges();

            tbl1.id_Responsavel = resp.id;
            tbl2.id_Responsavel = resp.id;
            tbl3.id_Responsavel = resp.id;

            db.Tabela1.add(tbl1);
            db.Tabela2.add(tbl2);
            db.Tabela3.add(tbl3);

            db.SaveChanges();
        }
        catch(Exception ex)
        {}
    }
}
    
28.08.2014 / 18:42