❔ 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
the error indicates that you are inserting an emplyoee for a department that doesn't exist
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();
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();
yes, you posted that
where does the exception throw?
context.SaveChanges();
which one?
the first
are you using nullable reference types?
public string? email { get; set; } filed email in employee
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 generatedthanks, u r right , i make department prop nullable, and solved, thanks again
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.