Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

EntityFramework Code First - Check if Entity is attached

I am trying to update an entity with a FK relationship in EntityFramework 4.3 Code First. I try to attach to the related entites by calling: Entry(item).State = EntityState.Unchanged

I get the following exception: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

I do not update these items nor have an id property for them on my main entity. Is it possible to know which entities are attached or not ?

Thanks in advance, Radu

question from:https://stackoverflow.com/questions/10027493/entityframework-code-first-check-if-entity-is-attached

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can find the answer here.

public bool Exists<T>(T entity) where T : class
{
    return this.Set<T>().Local.Any(e => e == entity);
}

Place that code into your context or you can turn it into an extension like so.

public static bool Exists<TContext, TEntity>(this TContext context, TEntity entity)
    where TContext : DbContext
    where TEntity : class
{
    return context.Set<TEntity>().Local.Any(e => e == entity);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...