problem is with foreign key:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_uzytkownik_Logowanie". The conflict occurred in database "Restauracja", table "dbo.Logowanie", column 'LoginID'.
The statement has been terminated.
I check this using breakpoints, and primary key in Logowanie
table was added when breakpoints (running application) was after
baza.SubmitChanges();
Primary key of LoginID
in logowanie
table is added automatically during SubmitChanges
.
How to copy value of LoginID
from logowanie
table to LoginID
in uztkownik
table? I add foreign key value here, but here LoginID
hasn't value yet.
Logowanie newlog = new Logowanie()
{
Login = model.LoginModel.Użytkownik,
Haslo = model.LoginModel.Hasło,
konto = model.LoginModel.Konto
};
uzytkownik user = new uzytkownik()
{
imie = model.uzytkownikModle.imie,
nazwisko = model.uzytkownikModle.nazwisko,
pesel = model.uzytkownikModle.pesel,
nip = model.uzytkownikModle.nip,
telefon = model.uzytkownikModle.telefon,
adres_zamieszkania = model.uzytkownikModle.adres_zamieszkania,
email = model.uzytkownikModle.email,
LoginID = newlog.LoginID //<<<----------------
};
baza.Logowanies.InsertOnSubmit(newlog);
baza.uzytkowniks.InsertOnSubmit(user);
baza.SubmitChanges();
uzytkownik should have a property called Logowanie, which you can set to the new instance you created but didn't Submit yet:
Since it's a foreign key relationship, your
Logowanie
class should contain a property forIQueryable<uzytkownik>
that is used to relate the objects properly in a one-to-many manner. As a result, there is no longer a need to assign the foreign key manually, it can be done through the object heirarchy:When I first ran across this it seemed a little backward to me, but once you break the relationships down into their class representations it really starts to make sense. It's also fantastic that it does all of the relationship assignments for you.