Get the primary key column from dbSet

3.2k Views Asked by At

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?

2

There are 2 best solutions below

3
On

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.

1
On

Found the answer.

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

     }
 }