简体   繁体   中英

How can I attach an existing entity to the entity framework context in generic?

I would like to load an entity with AsNoTracking and LazyLoadingEnabled = false in entity framework 6. In some special cases I would like to explicit reload some collections. How can I explicit load a collection of detached entity?

I'm looking for a generic option, to attaching an existing entity to the context.

My call looks like this:

var myCar = await this.myCarRepositoryAccessor.GetById(this.UnitOfWork, 1).ConfigureAwait(false);
this.UnitOfWork.LoadCollection(myCar, e => e.Driver);

GetById in DataRepository with looks like this:

public Task<TEntity> GetById(int id)
{
    return id == 0
        ? Task.FromResult(default(TEntity))
        : this.Context.InternalSet<TEntity>().AsNoTracking()?.SingleOrDefaultAsync(p => p.Id == id);
}

LoadCollection in UnitOfWork looks like:

public void LoadCollection<TEntity, TElement>(TEntity entity, Expression<Func<TEntity, ICollection<TElement>>> navigationProperty) where TEntity : class, IEntity where TElement : class
{
    //this.context.Entry(entity).State = EntityState.Unchanged
    this.context.Entry(entity).Collection(navigationProperty).Load();
}

I have tried to set the entity state to Unchanged but I get this error-message:

Attaching an entity of type 'MyCar' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

I guess it is because of AsNoTracking() , explicit load does not work with that.

you should remove it from your getbyid method if you want to use explicit loading.

also note that you can use string with collection so instead of attaching func you can simply use string, or list of strings in case you have more than one navigation to load.

It is good to know also that for collection you use collection and for single entity navigation you should use reference

The best thing you can do is adding another param to your getbyid string list, and include all the strings in that list, since include as well accepts string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM