C
C#9mo ago
eid

❔ How i can solve that in entityframworkcore

Unhandled exception. Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details. ---> Microsoft.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Employees_Departments_DepartmentID". The conflict occurred in database "secondbase", table "dbo.Departments", column 'DepartmentID'.
11 Replies
JakenVeina
JakenVeina9mo ago
the error indicates that you are inserting an emplyoee for a department that doesn't exist
eid
eid9mo ago
sorry, i can't understand what do u mean, the code is: using (mydbcontext context=new mydbcontext())//using()block for disbosing(removing unmanged resource) {
Department dp1=new Department(){name="engineering"}; Department dp2=new Department(){name="Hr"};
Employee emp=new Employee(){fname="ahmed",lastname="eid",address="alex"};
context.Departments.Add(dp1);//or context.Add(dp2); context.Add(course); context.Employees.Add(emp); context.SaveChanges();
JakenVeina
JakenVeina9mo ago
yes, you posted that where does the exception throw?
eid
eid9mo ago
context.SaveChanges();
JakenVeina
JakenVeina9mo ago
which one?
eid
eid9mo ago
the first
JakenVeina
JakenVeina9mo ago
are you using nullable reference types?
eid
eid9mo ago
public string? email { get; set; } filed email in employee
JakenVeina
JakenVeina9mo ago
my best guess, then, is that you didn't mark Department as nullable, so it's trying to insert a DepartmentID of 0 take a look at the SQL being generated
eid
eid9mo ago
thanks, u r right , i make department prop nullable, and solved, thanks again
Accord
Accord9mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts