I get the following error when I try to update a record:
The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.User_dbo.House_IdHouse\
My code:
public class User
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int IdUser { get; set; }
public int? IdHouse { get; set; }
[ForeignKey("IdHouse")]
public virtual House House { get; set; }
//--- other fields
}
public class House
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int IdHouse { get; set; }
public string Code { get; set; }
public virtual ICollection<User> Users { get; set; }
//--- other fields
}
I select users from database and update a flag then commit changes
var users = uow.Users.GetAll().Where(u => u.Name == null).ToList();
foreach (var user in users)
{
user.Checked = true;
}
uow.Users.UpdateMany(users);
uow.Commit();
I'm not updating the house property at all, however I have the feeling it tries to insert a new house.
This query returns 3 records. The first 2 records have "House" linked to it and for the last record the "House" property is set to null.
I also tried to update each record apart.
UpdateMany
function:
public void UpdateMany(IList<T> entities)
{
foreach (var entity in entities)
{
Update(entity);
}
}
public virtual void Update(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State == EntityState.Detached)
{
DbSet.Attach(entity);
}
dbEntityEntry.State = EntityState.Modified;
}
I also tried this one:
public virtual void Update(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
dbEntityEntry.State = EntityState.Modified;
}
I'm using .Net 4.0 and Entity Framework 6
UPDATE
Running SQL profiler i found something strange, the application tries to update then insert. Although i'm not doing any insert
Update:
exec sp_executesql N'UPDATE [dbo].[User] SET [DSL] = @0, [TPL] = @1, [DFD] = @2, [IdProff] = @3, [IdHouse] = @4 WHERE ([IdUser] = @5) ',N'@0 float,@1 float,@2 float,@3 int,@4 int,@5 int', @0=0,041837288150243422,@1=462,76900000000001, @2=19,360999999999997,@3=3354,@4=17@5=3354
Insert:
exec sp_executesql N'INSERT [dbo].[ IdUser]([ DSL], [TPL], [DFD], [IdProff], [IdHouse] VALUES (@0, @1, @2, @3, @4) SELECT [IdUser] FROM [dbo].[ IdUser] WHERE @@ROWCOUNT > 0 AND [IdUser] = scope_identity()',N'@0 float,@1 float,@2 float,@3 int,@4 int, @0=0,91810000000000003,@1=460,11399999999998,@2=19,792000000000002,@3=3197,@4=0 @5=N'User'
Why the application trying to insert?
UPDATE: My context settings
DbContext.Configuration.ProxyCreationEnabled = true;
DbContext.Configuration.LazyLoadingEnabled = true;
DbContext.Configuration.ValidateOnSaveEnabled = false;
DbContext.Configuration.AutoDetectChangesEnabled = false;