[英]How to get the primary key after insert in C#
I want to insert into 2 tables using c# and wpf, after getting the information that i need from wpf i try to insert.在从 wpf 获得我需要的信息后,我想使用 c# 和 wpf 插入 2 个表。 First I insert in the main table and it works, but when i try to get the primary key from that insertion in debug is 0 but in SSMS appear normal (ex 1200 or something), so i cannot insert in the second table which has a foreign key with the first one.
首先我在主表中插入并且它可以工作,但是当我尝试从调试中的插入中获取主键时是 0 但在 SSMS 中看起来很正常(例如 1200 或其他东西),所以我无法插入第二个有外键与第一个。 Any suggestion?
有什么建议吗?
var newsalariat = new Salariati
{
Nume = nume,
Prenume = prenume,
Data_angajare = data_angajare,
ID_birou = id_birou
};
context.Salariati.Add(newsalariat);
context.SaveChanges(); //it works and i can see it in ssms
int id_salariat_salariu = newsalariat.ID_angajat; //here i try to get the key for the second table
Console.WriteLine(id_salariat_salariu);
var newsalariu = new Salarii
{
ID_angajat = id_salariat_salariu,
Salariu_brut = salariu_brut,
Impozit = impozit,
Sporuri = sporuri
};
context.Salarii.Add(newsalariu);
context.SaveChanges(); //here i get the error
I want to insert into 2 tables using c# and wpf, after getting the information that i need from wpf i try to insert.在从 wpf 获得我需要的信息后,我想使用 c# 和 wpf 插入 2 个表。 First I insert in the main table and it works, but when i try to get the primary key from that insertion in debug is 0 but in SSMS appear normal (ex 1200 or something), so i cannot insert in the second table which has a foreign key with the first one.
首先我在主表中插入并且它可以工作,但是当我尝试从调试中的插入中获取主键时是 0 但在 SSMS 中看起来很正常(例如 1200 或其他东西),所以我无法插入第二个有外键与第一个。 Any suggestion?
有什么建议吗?
var newsalariat = new Salariati
{
Nume = nume,
Prenume = prenume,
Data_angajare = data_angajare,
ID_birou = id_birou
};
context.Salariati.Add(newsalariat);
context.SaveChanges(); //it works and i can see it in ssms
int id_salariat_salariu = newsalariat.ID_angajat; //here i try to get the key for the second table
Console.WriteLine(id_salariat_salariu);
var newsalariu = new Salarii
{
ID_angajat = id_salariat_salariu,
Salariu_brut = salariu_brut,
Impozit = impozit,
Sporuri = sporuri
};
context.Salarii.Add(newsalariu);
context.SaveChanges(); //here i get the error
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.