【问题标题】:Store update, insert, or delete statement affected an unexpected number of rows存储更新、插入或删除语句影响了意外数量的行
【发布时间】:2017-09-25 21:04:06
【问题描述】:

在 C# 中使用 EF6 :- 我有模型 A,里面有模型 B 和 C。

class A
{
    Guid Id;
    B b;
    C c;

    public A()
    {
        Id = new Guid;
    }
}

class B
{
    Guid Id;

    public B()
    {
        Id = new Guid;
    }
}

当模型 A 保存在数据库中(没有 B 和 C)时,它工作正常。当我从数据库中获取它然后创建新的 B 并将其分配给 A 并尝试保存它时。出现错误

存储更新、插入或删除语句影响了意外 行数 (0)。实体可能已被修改或删除 实体已加载。看 http://go.microsoft.com/fwlink/?LinkId=472540 获取有关信息 理解和处理乐观并发异常。

保存不公开外键的实体时出错 他们关系的属性。 EntityEntries 属性将 返回 null,因为无法将单个实体标识为源 的例外。可以进行保存时的异常处理 通过在实体类型中公开外键属性更容易。看 InnerException 了解详情。

(我将所有键作为 GUID)。 在进一步调试中,我可以看到异常中的 B 的 EntityKey 为空。

我已经厌倦了这个link1,link2,但这个解决方案都不起作用。

【问题讨论】:

  • 使用B Include()-ed 获取A

标签: c# mysql entity-framework


【解决方案1】:

首先我会使用属性而不是字段。

然后,正如我所见,AB 之间以及 AC 之间存在一对一的关系,其中 BC 是可选的。

"配置一对一关系时, 实体框架要求依赖的主键也是 外键。” - Julia Lerman 和 Rowan Miller 编写的《Programming Entity Framework Code First》

所以另一个问题是,在B 类中,您通过构造函数设置了Id 的值。

我会在下面试试这个:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace EFExposeForeignKey
{
    public class A
    {
        public A()
        {
            Id = Guid.NewGuid();
        }

        [Key]
        public Guid Id { get; set; }

        /* Other properties of A goes here */

        // Navigation property
        public B B { get; set; }

        // Navigation property
        public C C { get; set; }
    }

    public class B
    {
        [Key]
        [ForeignKey(nameof(EFExposeForeignKey.A.B))]
        // Or simply [ForeignKey("B")]
        // I wanted to emphasize here that "B" is NOT the type name but the name of a property in class "A"
        public Guid Id { get; set; }

        /* Other properties of B goes here */

        // Navigation property
        public A A { get; set; }
    }

    public class C
    {
        [Key]
        [ForeignKey(nameof(EFExposeForeignKey.A.C))]
        public Guid Id { get; set; }

        /* Other properties of C goes here */

        // Navigation property
        public A A { get; set; }
    }
}

【讨论】:

    猜你喜欢
    • 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
    相关资源
    最近更新 更多