【问题标题】:Why does Entity Framework try to insert existing entity?为什么实体框架会尝试插入现有实体?
【发布时间】:2018-03-31 13:16:12
【问题描述】:

我正在使用实体框架(使用代码优先方法),并且使用预期的外键和唯一键约束成功创建了数据库。

我有这两个模型类:

public class Foo 
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    public Bar Bar { get; set; } 
}

public class Bar
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    [Index(IsUnique = true), StringLength(512)]
    public string Url { get; set; }
}

还有这个应用代码:

var foo = GetData();

using (DatabaseContext db = new DatabaseContext())
{
    db.Entry(foo).State = EntityState.Added;

    if (foo.Bar != null)
    {
        var bar = await db.Bar.FirstOrDefaultAsync(x => x.Url == foo.Bar.Url);

        if (bar != null)
        {
            // When I assign an existing entity ...
            foo.Bar = bar;
        }
    }

    // ... following exception will be thrown.
    await db.SaveChangesAsync();
}

SqlException:无法在具有唯一索引“IX_Url”的对象“dbo.Bar”中插入重复的键行。重复键值为 (https://api.example.com/rest/v1.0/bar/FD6FAB72-DCE2-47DB-885A-424F3D4A70B6)。 声明已终止。

我不明白为什么 Entity Framework 试图添加导航属性 Bar,即使在从同一个 DbContext 获取和分配它之后也是如此。类似的 StackOverflow 问题尚未提供任何可行的解决方案。

如果我需要提供更多信息,请告诉我。

我是否忘记设置任何与 EF 相关的配置或类似的配置?提前谢谢!

【问题讨论】:

    标签: c# entity-framework ef-code-first data-annotations navigation-properties


    【解决方案1】:

    因为

    db.Entry(foo).State = EntityState.Added;
    

    也将foo.Bar(以及任何未被上下文跟踪的引用实体)标记为Added。

    您应该在添加Foo 实体之前解析引用的实体:

    var foo = GetData();
    using (DatabaseContext db = new DatabaseContext())
    {
        // Resolve references
        if (foo.Bar != null)
        {
            var bar = await db.Bar.FirstOrDefaultAsync(x => x.Url == foo.Bar.Url);
            if (bar != null)
                foo.Bar = bar;
        }
        // Then add the entity
        db.Entry(foo).State = EntityState.Added;
    
        await db.SaveChangesAsync();
    }
    

    【讨论】:

    • 这解决了我的问题。非常感谢亲爱的朋友! =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多