0

I have an

object elementToUpdate;

and i want to update it in my DbContext.

This seems to be a good starting point

public void Update<TEntity>(TEntity entity)
{
    DbContext.Set<TEntity>().Attach(entity);
    DbContext.Entry(entity).State = EntityState.Modified;
    DbContext.SaveChanges();
}

as explained here

My problem is, that i cannot cast my elementToUpdate properly. I know the name of it's precise type as string (e.g. "MyEntityType") but i don't know how to cast it using reflection - or in other words how to insert the Type-Parameter

DbContext.Set<MyEntityType>() 

from the string

"MyEntityType"

Thanks for your help.

Community
  • 1
  • 1
Martin Booka Weser
  • 3,192
  • 5
  • 28
  • 41
  • 1
    do you have MyEntityType in your code.if u have you can use factory pattern. – Arash Sep 03 '15 at 11:14
  • Do you really need to cast it, or do you just not know the type at compile time? If you just call `Update(elementToUpdate)` (without specifying the ``, it should automatically pick the right generic type for your template based on the parameter. – LInsoDeTeh Sep 03 '15 at 11:24
  • @LInsoDeTeh, if the entity boxed with `object` then the method would called by `TEntity` equal to `object` not the desired type. – Taher Rahgooy Sep 03 '15 at 14:46

2 Answers2

2

You always can use non-generic version of DbContext.Set:

DbContext.Set(ObjectContext.GetObjectType(entity.GetType()))

You can't use just entity.GetType() because it can be a proxy. That's why System.Data.Entity.Core.Objects.ObjectContext needed.

astef
  • 8,575
  • 4
  • 56
  • 95
0

Use other Set overload, which is not generic and accepts the type of entity as input, assuming you have the assembly qualified name of the object type(if the type is in the currently executing assembly, type name qualified by its namespace is sufficient ):

public void Update(object entity, string typeName)
{
    var type = Type.GetType(typeName);
    DbContext.Set(type).Attach(entity);
    DbContext.Entry(entity).State = EntityState.Modified;
    DbContext.SaveChanges();
}
Taher Rahgooy
  • 6,528
  • 3
  • 19
  • 30