gpt4 book ai didi

c# - Entity Framework 外键 InvalidOperationException

转载 作者:行者123 更新时间:2023-11-30 16:55:43 26 4
gpt4 key购买 nike

SaveChanges() 调用期间发生 InvalidOperationException 时,有没有办法以某种方式输出更多详细信息/信息?

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

我没有从数据库中删除任何内容,因此与此类似的问题对我没有帮助。该消息是不言自明的,没错,但我只是看不出代码中的错误,如果异常提供有关哪个属性和哪个外键有问题的更多信息,那将会很有帮助。

编辑 - 我检查了 InnerException,它是空的。

最佳答案

例如,如果你有下一个结构:

  public class Client
{
public int ClientID { get; set; }
public string Name { get; set; }

public int ClientTypeID { get; set; }
public ClientType ClientType { get; set; }
}

public class ClientType
{
public int ClientTypeID { get; set; }
public string Description { get; set; }
}

例如,如果您正在更改“Name”属性,您的属性“ClientType”必须为空,否则它将尝试创建、更新或删除您的客户端类型。

所以只需在 SaveChanges() 之前将 ClientType 设置为 null;

如果您发布更多代码,我们可以确定到底发生了什么,但这是我的猜测

关于c# - Entity Framework 外键 InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29090650/

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