C# 无法更改关系,因为一个或多个外键属性不可为null

C# 无法更改关系,因为一个或多个外键属性不可为null,c#,entity-framework-6,repository-pattern,C#,Entity Framework 6,Repository Pattern,例外情况: System.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

例外情况:

System.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.
我已经看到了一些解决上述问题的解决方案,如下所示。但没有一个对我有效:(可能是因为这些解决方案适用于EF 4.x版本。我的应用程序的EF版本是6.x


发生这种情况的原因是,当您将dto映射到实体时,先前相关的TaxMapLot将从TaxMapLots集合中删除,因为您的dto包含完整的图形

EF认为您的收藏项目是新的,以前的项目将被删除,因此它们的PropertyID将变为空。
您需要自己处理更新TaxMapLot的操作,而不是让mapper替您完成。

使外键属性ID在datatabase表IpTaxMapLots和TaxMapLot实体中都可以为空:

public virtual int? PropertyId { get; set; }

当然,您需要考虑,对于您的业务而言,拥有一个没有属性的TaxMapLot是否有意义。

您可以使用一些代码示例来解释您的解决方案吗?谢谢。是的,但首先您应该在问题中添加一些细节:更新时,您希望集合成员发生什么情况?您没有添加预期更新行为的细节vior在您的问题中有两个表。一个是
Properties
,另一个是
TaxMapLots
。关系为1:M。用户可以
添加/编辑或删除
TaxMapLot
表单上的记录。不能这样做。它必须在
Tax
表上有
propertId
。否则需要删除它。但我不知道如何删除它o删除它:(你知道吗?谢谢。要删除,只需在IpProperties表的IpTaxMapLots表中将cascade设置为delete。实际上,默认情况下它就在那里。
.PrimaryKey(t=>t.Id)。ForeignKey(“dbo.IpProperties”,t=>t.PropertyId,cascadeDelete:true)。Index(t=>t.PropertyId);
因此,您没有删除,因为某些原因,您只是在清空属性。此调用在做什么?--->wait\u propertyRepository.UpdateAsync(属性);我需要在此处编辑并保存更改。无需删除。谢谢。
public async Task<int> CreatePropertyAsync(CreateOrEditPropertyInput input)
        {
            var property = input.Property.MapTo<Property>();
            var propertyId = await _propertyRepository.InsertAndGetIdAsync(property);
            return propertyId;
        }
public virtual int? PropertyId { get; set; }