我有这个方法:
public void AddFile(MediaFileName mediaFile)
{
// Get a list of items which must be removed
var tmp = MediaFileNames.ToList().Where(m => m.FileName.Contains(mediaFile.FileType.ToString())).ToList(); // FileType is an enum
// remove each item from the Navigation property from memory
tmp.ForEach(f => MediaFileNames.Remove(f));
// Store items with an id in a list. This list is accessed by the presenter to delete these records
tmp.Where(f => f.Id != 0).ToList().ForEach(f => _filesToRemove.Add(f));
// Set the items filename
mediaFile.FileName = mediaFile.FileType.ToString() + new FileInfo(mediaFile.SourceFile).Extension;
// Add the item to the navigation property
MediaFileNames.Add(mediaFile);
}
MediaFilesNames是Media类的导航属性。
我保留了一个必须从数据库中删除的项目列表(_filesToRemove)。此列表可从我的存储库访问:
public bool Update(Act act)
{
foreach (var file in act.Media.FilesToRemove)
{
if (_context.MediaFileNames.FirstOrDefault(f => file.Id == f.Id) != null)
_context.MediaFileNames.DeleteObject(file);
}
_context.SaveChanges();
return true;
}
当调用SaveChanges时,我收到此消息:
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.
我不明白为什么我收到此消息,因为我正在删除现有项目,而我只添加一个新项目。我希望你能帮助我。
答案 0 :(得分:1)
尝试检查数据库中的关系,并指定其删除规则必须以级联模式完成。
或者,尝试检查相关表中的外键,并将其ALLOW NULL值设置为true。您可以做的是为有罪列使用索引并为它们添加唯一约束,以便您可以将它们用作关系中的外键。
如果列是主键的一部分,则无法将ALLOW NULL设置为true。