使用Entity Framework更新记录时出错

时间:2017-01-23 18:04:48

标签: c# entity-framework

当我尝试更新记录时出现以下错误:

  

INSERT语句与FOREIGN KEY约束冲突   \" FK_dbo.User_dbo.House_IdHouse \

我的代码:

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
}

我从数据库中选择用户并更新标志然后提交更改

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();

我根本没有更新房产,但我觉得它试图插入新房。

此查询返回3条记录。前两个记录有&#34; House&#34;与它相关联并且最后记录了#34; House&#34; property设置为null。

我还尝试将每条记录更新。

UpdateMany功能:

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;
}

我也试过这个:

public virtual void Update(T entity)
{
    DbEntityEntry dbEntityEntry = DbContext.Entry(entity);

    dbEntityEntry.State = EntityState.Modified;
}

我正在使用.Net 4.0和Entity Framework 6

  

更新

运行SQL分析器我发现一些奇怪的东西,应用程序尝试更新然后插入。 虽然我没有做任何插入

更新

  

exec sp_executesql N&#39; UPDATE [dbo]。[User] SET [DSL] = @ 0,[TPL] = @ 1,   [DFD] = @ 2,[IdProff] = @ 3,[IdHouse] = @ 4 WHERE([IdUser] = @ 5)   &#39;,N&#39; @ 0 float,@ 1 float,@ 2 float,@ 3 int,@ 4 int,@ 5 int&#39;,   @ 0 = 0,041837288150243422,@ 1 = 462,76900000000001,   @ 2 = 19,360999999999997,@ 3 = 3354,@ 4 = 17 @ 5 = 3354

插入:

  

exec sp_executesql N&#39; INSERT [dbo]。[IdUser]([DSL],[TPL],[DFD],   [IdProff],[IdHouse] VALUES(@ 0,@ 1,@ 2,@ 3,@ 4)SELECT [IdUser] FROM   [dbo]。[IdUser] WHERE @@ ROWCOUNT&gt; 0 AND [IdUser] =   scope_identity()&#39;,N&#39; @ 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&#39;用户&#39;

为什么应用程序试图插入?

更新: 我的上下文设置

DbContext.Configuration.ProxyCreationEnabled = true;
DbContext.Configuration.LazyLoadingEnabled = true;
DbContext.Configuration.ValidateOnSaveEnabled = false;
DbContext.Configuration.AutoDetectChangesEnabled = false;

0 个答案:

没有答案