简体   繁体   中英

How to update entities in the DbContext without knowing their exact Type?

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 (eg "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.

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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM