Save fk right after pk is generated with Entity

Asked

Viewed 78 times

0

I have a system and this system has some tables that are associative. As soon as I write the main table in the comic book, I need to make sure that that new generated PK is recorded in three other tables, but you have to make sure it’s the one generated. The system runs on the web and it needs to be avoided that someone else is using the same routine and fire another PK, entede?

Here Gero 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)
                {}
            }
        }
  • I don’t know much about Ntity, but try it like this; db.SaveChanges();, adds a var id = resp.id; to get the last inserted ID

1 answer

1


At the end of recording, go get the id table Responsavel won’t solve your 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)
        {}
    }
}
  • So I thought, then one person said that there are resources in Sql Server that "like freezing that id", but did not give me any more information. If there are two Inserts at the same time. How will you behave? That’s my concern.

  • The id will always be incremental, if there are two Inserts simultaneously I doubt that Sqlserver will burst, because it processes one order at a time. Now I can’t tell you anything for sure...

  • Okay, thanks. I’m going that way too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.