简体   繁体   English

实体框架外键InvalidOperationException

[英]Entity Framework foreign key InvalidOperationException

Is there a way to somehow output more details/information when InvalidOperationException like this one happens during SaveChanges() call? 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. 如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。

I am not removing anything from the DB so questions similar to this one didn't help me. 我没有从数据库中删除任何内容,所以类似于这个的问题对我没有帮助。 The message is quite self-explanatory, true, but I just can't see the mistake in code and it would be helpful if the exception gave more information about which property and which foreign key is in question. 这条消息是不言自明的,是真的,但我只是看不到代码中的错误,如果异常提供了有关哪个属性和哪个外键有问题的更多信息,那将会有所帮助。

EDIT - I have checked the InnerException and it's empty. 编辑 - 我检查了InnerException并且它是空的。

For example, if you have the next structure: 例如,如果您有下一个结构:

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

If you are changing the "Name" propertie for example, your property "ClientType" must be null, otherwise it will try to create,update or delete your client type. 例如,如果要更改“名称”属性,则属性“ClientType”必须为null,否则它将尝试创建,更新或删除您的客户端类型。

So just set the ClientType to null, before SaveChanges(); 因此,在SaveChanges()之前将ClientType设置为null;

If you post more of your code, we can be sure what exactlly it's happening, but this was my guess 如果您发布更多代码,我们可以确定它发生了什么,但这是我的猜测

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM