gpt4 book ai didi

c# - 存储更新、插入或删除语句影响了意外数量的行

转载 作者:行者123 更新时间:2023-11-29 18:23:03 25 4
gpt4 key购买 nike

在 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 并尝试保存它时。出现错误

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

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

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

最佳答案

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

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

"When configuring one-to-one relationships, Entity Framework requires that the primary key of the dependent also be the foreign key." - Programming Entity Framework Code First by Julia Lerman & Rowan Miller

所以另一个问题是,在类 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; }
}
}

关于c# - 存储更新、插入或删除语句影响了意外数量的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46414165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com