问题
Using EF5 with a generic Repository Pattern and ninject for dependency injenction and running into an issue when trying to update an entity to the database utilizing stored procs with my edmx.
my update in DbContextRepository.cs is:
public override void Update(T entity)
{
if (entity == null)
throw new ArgumentException("Cannot add a null entity.");
var entry = _context.Entry<T>(entity);
if (entry.State == EntityState.Detached)
{
_context.Set<T>().Attach(entity);
entry.State = EntityState.Modified;
}
}
From my AddressService.cs which goes back to my repository I have:
public int Save(vw_address address)
{
if (address.address_pk == 0)
{
_repo.Insert(address);
}
else
{
_repo.Update(address);
}
_repo.SaveChanges();
return address.address_pk;
}
When it hits the Attach and EntityState.Modified it pukes with the error:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
I have looked through many of the suggestions in stack and on the Internet and not coming up with anything that resolves it. Any work arounds would be appreciated.
Thanks!
回答1:
Edit: Original answer used Find
instead of Local.SingleOrDefault
. It worked in combination with @Juan's Save
method but it could cause unnecessary queries to database and else
part was probably never executed (executing the else part would cause exception because Find already queried the database and hadn't found the entity so it could not be updated). Thanks to @BenSwayne for finding the issue.
You must check if an entity with the same key is already tracked by the context and modify that entity instead of attaching the current one:
public override void Update(T entity) where T : IEntity {
if (entity == null) {
throw new ArgumentException("Cannot add a null entity.");
}
var entry = _context.Entry<T>(entity);
if (entry.State == EntityState.Detached) {
var set = _context.Set<T>();
T attachedEntity = set.Local.SingleOrDefault(e => e.Id == entity.Id); // You need to have access to key
if (attachedEntity != null) {
var attachedEntry = _context.Entry(attachedEntity);
attachedEntry.CurrentValues.SetValues(entity);
} else {
entry.State = EntityState.Modified; // This should attach entity
}
}
}
As you can see the main issue is that SingleOrDefault
method needs to know the key to find the entity. You can create simple interface exposing the key (IEntity
in my example) and implement it in all your entities you want to process this way.
回答2:
I didn't want to pollute my auto generated EF classes by adding interfaces, or attributes. so this is really a little bit from some of the above answers (so credit goes to Ladislav Mrnka). This provided a simple solution for me.
I added a func to the update method that found the integer key of the entity.
public void Update(TEntity entity, Func<TEntity, int> getKey)
{
if (entity == null) {
throw new ArgumentException("Cannot add a null entity.");
}
var entry = _context.Entry<T>(entity);
if (entry.State == EntityState.Detached) {
var set = _context.Set<T>();
T attachedEntity = set.Find.(getKey(entity));
if (attachedEntity != null) {
var attachedEntry = _context.Entry(attachedEntity);
attachedEntry.CurrentValues.SetValues(entity);
} else {
entry.State = EntityState.Modified; // This should attach entity
}
}
}
Then when you call your code, you can use..
repository.Update(entity, key => key.myId);
回答3:
You can actually retreive the Id through reflection, see example below:
var entry = _dbContext.Entry<T>(entity);
// Retreive the Id through reflection
var pkey = _dbset.Create().GetType().GetProperty("Id").GetValue(entity);
if (entry.State == EntityState.Detached)
{
var set = _dbContext.Set<T>();
T attachedEntity = set.Find(pkey); // access the key
if (attachedEntity != null)
{
var attachedEntry = _dbContext.Entry(attachedEntity);
attachedEntry.CurrentValues.SetValues(entity);
}
else
{
entry.State = EntityState.Modified; // attach the entity
}
}
回答4:
@serj-sagan you should do it in this way:
**Note that YourDb should be a class derived from DbContext.
public abstract class YourRepoBase<T> where T : class
{
private YourDb _dbContext;
private readonly DbSet<T> _dbset;
public virtual void Update(T entity)
{
var entry = _dbContext.Entry<T>(entity);
// Retreive the Id through reflection
var pkey = _dbset.Create().GetType().GetProperty("Id").GetValue(entity);
if (entry.State == EntityState.Detached)
{
var set = _dbContext.Set<T>();
T attachedEntity = set.Find(pkey); // access the key
if (attachedEntity != null)
{
var attachedEntry = _dbContext.Entry(attachedEntity);
attachedEntry.CurrentValues.SetValues(entity);
}
else
{
entry.State = EntityState.Modified; // attach the entity
}
}
}
}
回答5:
Another solution (based on @Sergey's answer) could be:
private void Update<T>(T entity, Func<T, bool> predicate) where T : class
{
var entry = Context.Entry(entity);
if (entry.State == EntityState.Detached)
{
var set = Context.Set<T>();
T attachedEntity = set.Local.SingleOrDefault(predicate);
if (attachedEntity != null)
{
var attachedEntry = Context.Entry(attachedEntity);
attachedEntry.CurrentValues.SetValues(entity);
}
else
{
entry.State = EntityState.Modified; // This should attach entity
}
}
}
And then you would call it like this:
Update(EntitytoUpdate, key => key.Id == id)
回答6:
Without reflection and if you don't want to use interfaces, you can use functional delegates to find an entity in the database. Here is the updated sample from above.
private void Update<T>(T entity, Func<ObservableCollection<T>, T> locatorMap) where T : class
{
var entry = Context.Entry(entity);
if (entry.State == EntityState.Detached)
{
var set = Context.Set<T>();
T attachedEntity = locatorMap(set.Local);
if (attachedEntity != null)
{
var attachedEntry = Context.Entry(attachedEntity);
attachedEntry.CurrentValues.SetValues(entity);
}
else
{
entry.State = EntityState.Modified; // This should attach entity
}
}
}
You would call it like this:
Update(EntitytoUpdate, p => p.SingleOrDefault(a => a.Id == id))
回答7:
If you set your context to AsNoTracking() this will stop aspmvc tracking the changes to the entity in memory (which is what you want anyway on the web).
_dbContext.Products.AsNoTracking().Find(id);
I would recommend you read more about this at http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/advanced-entity-framework-scenarios-for-an-mvc-web-application
回答8:
Detaching the entity found (see attachedEntity
in Ladislav's solution) and re-attaching the modified one worked for me just fine.
The reasoning behind this is simple: if something's immutable then replace it (as a whole, entity) from where it belongs with the desired one.
Here's an example of how to do this:
var set = this.Set<T>();
if (this.Entry(entity).State == EntityState.Detached)
{
var attached = set.Find(id);
if (attached != null) { this.Entry(attached).State = EntityState.Detached; }
this.Attach(entity);
}
set.Update(entity);
Of course, one may easily figure out that this snippet is part of a generic method, hence the use of T
, which is a template parameter, and Set<T>()
.
回答9:
That answer above may be EF 4.1+. For those on 4.0, try this simple method...not really tested but did attach and save my changes.
public void UpdateRiskInsight(RiskInsight item)
{
if (item == null)
{
throw new ArgumentException("Cannot add a null entity.");
}
if (item.RiskInsightID == Guid.Empty)
{
_db.RiskInsights.AddObject(item);
}
else
{
item.EntityKey = new System.Data.EntityKey("GRC9Entities.RiskInsights", "RiskInsightID", item.RiskInsightID);
var entry = _db.GetObjectByKey(item.EntityKey) as RiskInsight;
if (entry != null)
{
_db.ApplyCurrentValues<RiskInsight>("GRC9Entities.RiskInsights", item);
}
}
_db.SaveChanges();
}
回答10:
You may have forgotten to instaçia the object fBLL = new FornecedorBLL();
in algun place
来源:https://stackoverflow.com/questions/12585664/an-object-with-the-same-key-already-exists-in-the-objectstatemanager-the-object