我通常有我要删除的主实体,但在本例中,我试图通过导航属性删除它
var person = await dbContext.Person
.Include(x => x.Phone)
.FirstOrDefaultAsync(d => d.PersonKey == key, cancellationToken);
person.Phones.Remove(phoneToDelete);
await dbContext.SaveChangesAsync();
我在SaveChangesAsync()
上得到了以下异常
Exception thrown: 'System.InvalidOperationException' in Microsoft.EntityFrameworkCore.dll: 'The association between entity types 'Person' and 'Phone' has been severed, but the relationship is either marked as required or is implicitly required because the foreign key is not nullable. If the dependent/child entity should be deleted when a required relationship is severed, configure the relationship to use
个
以下代码可以正常工作:
dbContext.Remove(phoneToDelete);
await dbContext.SaveChangesAsync();
所以,当然我确实让它工作了,但我认为原始代码应该可以工作,并想知道为什么它不能.