3

I want to write a function, which receives any Entity object and finds the current value by automatically determined primary key and updates it.

Could you please point me any direction.

 public void Update(object entity)
 {
     using (var _db = new MyEntities())
     {
        var table  = _db.Set(entity.GetType());
//Here we should somehow find the entity object which primary key coincides with the one of entity
        var entityObj = table.FindObjectByPrimaryKey(entity);
        entityObj.CopyDataFrom(entity);
        _db.SaveChanges()

     }
}

Is this possible?

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
Vahagn
  • 386
  • 2
  • 21

2 Answers2

4

you can find primary keys of an entity like this

ObjectContext objectContext = ((IObjectContextAdapter)_db).ObjectContext;
ObjectSet<YourEntity> set = objectContext.CreateObjectSet<YourEntity>();
IEnumerable<string> keyNames = set.EntitySet.ElementType
                                            .KeyMembers
                                            .Select(k => k.Name);

and then use reflection to access their values.

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
  • I don't have the `YourEnity` class here. What can I do is dynamically get the type of the entity instance: `entity.GetType()`. – Vahagn Dec 08 '14 at 09:31
  • @Vahagn You should make your method generic to begin with. – Gert Arnold Dec 08 '14 at 10:57
  • Adding on doctor's solution, according to https://michaelmairegger.wordpress.com/2013/03/30/find-primary-keys-from-entities-from-dbcontext/#comment-156, there are improvements to be made (such as performance) to this approach. – Veverke Mar 30 '15 at 15:55
-2

Found the answer.

 public void Update(object entity)
 {   
     using (var _db = new MyEntities())
     {           
        _db.Entry(entity).State = System.Data.Entity.EntityState.Modified;             
        _db.SaveChanges();

     }
 }
Vahagn
  • 386
  • 2
  • 21