Я хотел бы сделать динамический вызов метода Add в DbSet, который я не знаю при компиляции.
На самом деле, это возможно с простым отражением, но производительность ужасна.Вот код, который мы используем сейчас:
Type contextType = (context as Object).GetType();
var set = (contextType.GetProperty(entitySetName)).GetValue(context, null);
Type typeSet = set.GetType();
MethodInfo method = typeSet.GetMethod("Add");
Object[] args = { entity };
method.Invokke(set, args);
я пробовал две другие возможности с разными ошибками.
Первый - использование делегата
public delegate void MyDel<T>(T t,object entity);
Type contextType = (context as Object).GetType();
var set = (contextType.GetProperty(entitySetName)).GetValue(context, null);
Type typeSet = set.GetType();
MethodInfo method = typeSet.GetMethod("Add");
Type template = typeof(MyDel<>);
Type specific = template.MakeGenericType(childClassType);
Delegate test = Delegate.CreateDelegate(specific, method);
но в последней строке я получаю следующую ошибку: Ошибка привязки к целевому методу
И третий вариант - использовать дерево выражений следующим образом:
Type contextType = (context as Object).GetType();
var set = (contextType.GetProperty(entitySetName)).GetValue(context, null);
Type typeSet = set.GetType();
MethodInfo method = typeSet.GetMethod("Add");
ParameterExpression paramo = Expression.Parameter(typeSet, "param");
ParameterExpression parami = Expression.Parameter(typeSet, "newvalue");
Expression convertedParamo = Expression.Convert(paramo, typeof(Object));
Expression convertedParami = Expression.Convert(parami, typeof(Object));
MethodCallExpression methodCall = Expression.Call(convertedParamo, method, convertedParami);
Expression valueExp = Expression.Lambda(methodCall, paramo, parami);
Expression<Action<Object, Object>> dynamicExpression = (Expression<Action<Object, Object>>)valueExp;
Action<Object, Object> dynamicAction = dynamicExpression.Compile();
Object o = Activator.CreateInstance(otherType);
dynamicAction(o, entity);
Но в этом случаев строке "Expression.Call (convertParamo, метод, ..
я получил эту ошибку:
Метод 'DictionnaireONYX.Entites.ArticleSansFacturier Добавить (DictionnaireONYX.Entites.ArticleSansFacturier)'объявленный для типа 'System.Data.Entity.DbSet`1 [DictionnaireONYX.Entites.ArticleSansFacturier]' не может быть вызван с экземпляром типа System.Object *
, где ArticleSansFacturier - это DbSet.
Кто может мне помочь?
Заранее спасибо