Get primary key column from dbSet
I want to write a function that takes any object Entity
and finds the current value by the auto-determined primary key and updates it.
Could you please point me in the 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 it possible?
+3
source to share
2 answers
you can find entity primary keys 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.
+4
source to share