I am using EF6 with the Generic Repository template. I recently had a problem trying to delete a compound object at a time. Here is a simplified scenario:
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Parent")]
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
To remove the parent with related children, I do something like this:
public virtual T GetById(int id)
{
return this.DBSet.Find(id);
}
public virtual void Delete(T entity)
{
DbEntityEntry entry = this.Context.Entry(entity);
if (entry.State != EntityState.Deleted)
{
entry.State = EntityState.Deleted;
}
else
{
this.DBSet.Attach(entity);
this.DBSet.Remove(entity);
}
}
First, I find the parent object by identifier, and then pass it to the delete method to change its state for deletion. The .SaveChanges () context finally completes the deletion.
Everything went perfectly. The find method only stopped the Parent object, and the Delete function worked, since I have a cascade on deletion that is included in Children.
But the moment I added another property to the Child class:
[ForeignKey("Gender")]
public int GenderId { get; set; }
public virtual Gender Gender { get; set; }
- EF Parent.Find(). - :
: , NULL. , . , , , .
( Gender) . !
, , .
, :
- LazyLoading false - this.Configuration.LazyLoadingEnabled = false; , , .
- , . , , .
- Remove() , EntityState Deleted. , EntityState.
- , EF , ?