我的课程定义如下:
public class Subject
{
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set;
[ForeignKey("LevelId")]
public Level Level { get; set; }
[ForeignKey("ParentId")]
public Subject Parent { get; set; }
public ICollection<Subject> Children { get; set; }
}
然后创建一个方法:
public int Create(Subject newSubject)
{
var subjectToAdd = _mapper.Map<dataModels.Subject>(newSubject);
_context.Add(subjectToAdd);
SaveChildren(subjectToAdd.Id, newSubject.LevelId, newSubject.Children);
_context.SaveChanges();
return subjectToAdd.Id;
}
我的问题是孩子们两次得救,一次进入:
_context.Add(subjectToAdd);
因为在映射期间,子映射,然后再次映射
SaveChildren();
我想要实现的是EF忽略Children集合中的更改,然后我将在SaveChildren()中手动保存更改。
我尝试添加这个:
var subjectToAdd = _mapper.Map<dataModels.Subject>(newSubject);
_context.Add(subjectToAdd);
_context.Entry(user).Property(x => x.Children).IsModified = false; // this line
但它不起作用。还尝试使其为null但它说了一些关于切断的错误。如何在不删除该属性的情况下使EF忽略Children集合,然后我只执行自己的保存逻辑?
答案 0 :(得分:0)
您可以将Children
的条目状态更改为Unchanged
,以避免在应用SaveChanges
时插入它们。
在手动插入子项之前,您应该保存Subject
。应该生成newSubject.Id
。
此外,正在映射newSubject
,这是不必要的。所以,我修改了这样的Create
方法;
public int Create(Subject newSubject)
{
// The newSubject entry state has been changed as 'Added'
_context.Subjects.Add(newSubject);
// The children of newSubject entry state has been changed as 'Unchanged' and children will not be inserted
_context.Entry(newSubject.Children).State = EntityState.Unchanged;
//Save the newSubject entity
_context.SaveChanges();
//Save the children
SaveChildren(newSubject.Id, newSubject.LevelId, newSubject.Children);
return newSubject.Id;
}