I am absolutely new to 开发者_Python百科Entity Framework so please don't hesitate to point any errors. Anyway I'll try to describe my problem as I understand it.
I am creating a n-Tier application with Entity Framework. I am also using a generic repository as described in this page.
I was successful in populating a DetailsView
and inserting a value to the database through an ObjectDataSource. However the problem I am encountering occurs when I am updating.
The error that I get is
An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager. Verify that the key values of the supplied object match the key values of the object to which changes must be applied.
And I understand WHY it happens as well. I use the following methods to populate the values from the DB.
public IEnumerable<TEntity> GetAll<TEntity>() where TEntity : class
{
return GetQuery<TEntity>().AsEnumerable();
}
public List<Company> GetAllCompanies()
{
return _genericRepository.GetAll<Company>().ToList();
}
If I put a breakpoint in the GetAll
method and observe the results I see that anEntityKey
is set and IsChangeTracked
is true for each object in the list.
But if I check the object passed to the UpdateMethod
specified for the ObjectDataSource
, then EntityKey
is null, EntityState
is detached and IsChangeTracked
is false. So because the EntityKey is null, I understand the exception is valid.
My update method looks like
public void Update<TEntity>(TEntity entity) where TEntity : class
{
ObjectSet<TEntity> objSet = DataContext.CreateObjectSet<TEntity>();
objSet.ApplyCurrentValues(entity);
SaveChanges();
}
I tried to attach using objSet.Attach(entity);
then no exceptions but the object does not get updated either.
How do I properly perform the update using DetailsView ? Or how do I properly bind an ObjectDataSource
to a DetailsView
? How do I make sure that my EntityKey does not become null ?
Solved the issue using the method shown below
public void Update<TEntity>(TEntity entity) where TEntity : class
{
object originalItem;
EntityKey key = DataContext.CreateEntityKey(GetEntityName<TEntity>(), entity);
if (DataContext.TryGetObjectByKey(key, out originalItem))
{
DataContext.ApplyCurrentValues(key.EntitySetName, entity);
}
SaveChanges();
}
精彩评论