EF impatiently loads problem with navigational properties

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 , ?

+4
1

, . Unit Of Work , ninject.

kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();

UnitOWork IDisposable.

public bool DeleteView(int viewId)
    {
        // This is a workaround. It seems ninject is not disposing the context. 
        // Because of that all the info (navigation properties) of a newly created view is presisted in the context.
        // Hence you get a referential key error when you try to delete a composite object.
        using (var context = new ApplicationDbContext())
        {
            var repo = new GenericRepository<CustomView>(context);
            var view = repo.GetById(viewId);
            repo.Delete(view);
            context.SaveChanges();
        }
        //var model = _unitOfWork.CustomViews.GetById(viewId);
        //_unitOfWork.CustomViews.Delete(model);
        //_unitOfWork.Save();

        return true;
    }

, ( ). CustomView ( ). .

, , . , - Ninject UnitOfWork, . GetById() - .

. , -.

+2

Source: https://habr.com/ru/post/1666824/


All Articles