mercredi 21 janvier 2015

Using reflection to feed Collection in DbEntityEntry

for some reason I'm trying to dynamically count the number of item of a related collection of an entity.


Dynamically write the equivalent of



Int32 i = Entry(client).Collection(x => x.Contacts).Query().Count();


The dynamic part being on x => x.Contacts. So:



Client client = Clients.First();
Type t = typeof(Client);
var param = Expression.Parameter(t, "x" );
PropertyInfo pi = t.GetProperty("Contacts");
MemberExpression expr = Expression.Property(param, pi);
var exp = Expression.Lambda(expr, param);


from here the following runs



Int32 i = Entry(client).Collection(
(Expression<Func<Cclb.Domain.Entities.Client, ICollection<Cclb.Domain.Entities.ClientContact>>>)
exp).Query().Count();


but not



//same without the cast
Int32 i = Entry(client).Collection(exp).Query().Count();


it raises:



Impossible to convert from 'System.Linq.Expressions.LambdaExpression' to 'string'


That is, it does not call the 'good' method. Is it possible to have it runs without the cast ?






Aucun commentaire:

Enregistrer un commentaire