我的目标是有大量的插入/更新操作来实现。 域模型由相关文件夹实体图片实体尽可能多到一的。实体框架的关系,AutoDetectChanges =假问题
通常我将图像添加到数据库背景是这样的:
var folder = dbContext.Folders.First();
var image = new Image();
image.Folder = folder;
image.<SomeFields> = "<SomeData>";
dbContext.Images.Add(image);
dbContext.SaveChanges();
为了有更好的表现我关掉自动更改跟踪:
dbContext.Configuration.AutoDetectChangesEnabled = false;
现在我得到一个错误:
Entities in 'DbContext.Images' participate in the 'Image_Folder' relationship. 0 related 'Image_Folder_Target' were found. 1 'Image_Folder_Target' is expected.
我试着使用:
folder.Images.Add(image);
dbContext.Entry(folder).State = EntityState.Modified;
,但它并没有帮助。
我应该如何修正错误?
UPD:固定代码段
UPD2:简化实体(从基类去除继承(以使代码的可读性),最不必要的属性):
Image.cs
public class Image
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string AuthorName { get; set; }
public string AuthorUrl { get; set; }
[StringLength(255)]
[Required]
[Column(TypeName = "VARCHAR")]
public new string File { get; set; }
[Required]
public bool IsCover { get; set; }
[Required]
public int Order { get; set; }
public virtual Product Product { get; set; }
[Required]
public virtual Folder Folder { get; set; }
public override string ToString()
{
return File;
}
public Image()
{
Order = 1;
}
}
Folder.cs
public class Folder
{
public int Id { get; set; }
public virtual Folder Parent { get; set; }
public virtual ICollection<Image> Images { get; set; }
public virtual ICollection<Folder> Folders { get; set; }
public string Name { get; set; }
public override string ToString()
{
return Name;
}
public Folder()
{
Images = new HashSet<Image>();
}
}
我测试你的代码,没有例外发生,但没有数据输入到数据库 –