Ignore a collection member in EF Core

entity-framework entity-framework-core

Question

I have class defined like this:

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; }
}

And then a method to create:

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;
}

My problem is that children are twice saved, once in:

_context.Add(subjectToAdd);

because during mapping, the Children are mapped, and then once again in

SaveChildren();

What I want to achieve is for EF to ignore changes in the Children collection and then I will save the changes manually in SaveChildren().

I tried adding this:

var subjectToAdd = _mapper.Map<dataModels.Subject>(newSubject);
_context.Add(subjectToAdd);
_context.Entry(user).Property(x => x.Children).IsModified = false;  // this line

but it did not work. Also tried making it null but it said something about severed error. How do I make EF ignore the Children collection without deleting that property and then I just do my own save logic?

1
1
12/24/2017 4:51:11 AM

Popular Answer

You could just change the entry state of the Children as Unchanged to avoid insert them when SaveChanges has been applied.

You should save Subject before inserting the children manually. newSubject.Id should be generated.

Also, newSubject is being mapped and it is unnecessary. So, I modified the Create method like this;

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;
}
0
12/24/2017 12:58:26 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow