在调用通用反射方法

时间:2015-07-22 20:33:24

标签: c# exception generics reflection azure-mobile-services

所以这个问题很混乱。它相当复杂和抽象,所以我会尽力解释它。

我有3个班级LinkedInFacebookTwitter。所有这些都继承自公共基类SocialBase,它只有一个属性uuid,并且只使用此属性,因此我们可以在数据库中找到实际类型。

所以我有这个函数接受一个Profile类,它包含所有LinkedInFacebookTwitter表的外键,以及一个枚举值这将告诉我们是否要查找LinkedInFacebookTwitter外键

public static async Task UnlinkSocialAccountFromProfile(Profile prof, SocialNetworks provider)
    {
        //TYPE variable of LinkedIn, Facebook, or Twitter
        var handler = HandlerMapping[provider];
        //client is MobileServiceClient
        var method = client.GetType().GetMethod("GetTable", Type.EmptyTypes);
        //MobileServiceClient.GetTable<handler>()
        var generic = method.MakeGenericMethod(handler);
        //IMobileServiceTable<handler> 
        var table = generic.Invoke(client, null);
        //Profile has 3 foreign keys, LinkedinUUID, FacebookUUID, TwitterUUID, we want the <handler>UUID
        string propertyValue = prof.GetType().GetProperty(handler.Name + "UUID").GetValue(prof) as string;
        //Invoke Extension method with our generic types
        var genMethod =
            typeof (Extensions).GetMethod("FilterByNamedProperty")
                .MakeGenericMethod(table.GetType().GetGenericArguments()[0], propertyValue.GetType());
        //Get the List<handler> that results from our query
        var result = await (Task<List<Linkedin>>)(genMethod.Invoke(null, new [] {table, "uuid", propertyValue}));
        //var result = await (table as IMobileServiceTable<SocialBase>).FilterByNamedProperty("uuid", propertyValue);
        await new SocialResources().DeleteIfExists((result as IList<SocialBase>)[0]);
}

所以我在这里做的是获取类的Type,所以这将是SocialBase子类之一。对于这个特殊的例子,我知道我将会寻找LinkedIn类型。所以在获得类型LinkedIn后,我需要从我的MobileServiceTable调用泛型方法,所以通常它看起来像MobileServiceTable.GetTable<LinkedIn>()但是由于反射,我们必须采取更长的路径。

获得我返回的IMobileServiceTable<LinkedIn>实例后,我得到了我正在寻找的外键值。在这种情况下,它将被称为LinkedInUUID。现在这里是棘手的部分。我有这个扩展方法,它将为我构造我的查询表达式,因为它必须是Expression<Func<LinkedIn, bool>>

类型
public async static Task<List<TSource>> FilterByNamedProperty<TSource, TValue>(this IMobileServiceTable<TSource> source, string propertyName, TValue value)
    {
        // uuid
        var property = typeof(TSource).GetProperty(propertyName);
        // (TSource)p
        var parExp = Expression.Parameter(typeof(TSource));
        //p.uuid
        var methodExp = Expression.Property(parExp, property);
        // value
        var constExp = Expression.Constant(value, typeof(TValue));
        // p.uuid == value
        var binExp = Expression.Equal(methodExp, constExp);
        // p => p.uuid == value
        var lambda = Expression.Lambda<Func<TSource, bool>>(binExp, parExp);
        return await source.Where(lambda).ToListAsync(); 
    }

我相信这些评论在每个语句发生时都能很好地解释构建过程。但是,一旦我们到达return await ...,应用程序将崩溃。这是该行之前的输出和紧随其后的错误。

IMobileServiceTable<TSource> source = {Microsoft.WindowsAzure.MobileServices.MobileServiceTable<SocialConnect.Linkedin>}(正确)

propertyName = uuid(正确)

TValue value = dscRJQSIxJaEfd(正确)

我强烈地感觉问题出在我的lambda表达式上,但如果我使用此行var test = await (source as IMobileServiceTable<Linkedin>).Where(p => p.uuid == (value as string)).ToListAsync();测试扩展程序,它的效果非常好。但是一旦我将其更改为使用lambda变量,我就会获得异常。 lambda表达式的实际值是{Param_0 => (Param_0.uuid == "dscRJQSIxJaEfd")},看起来正确

有什么想法吗?

修改 对不起,这是堆栈跟踪的实际异常

`A first chance exception of type 'System.NullReferenceException' occurred in mscorlib.dll
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.WindowsAzure.MobileServices.Query.FilterBuildingExpressionVisitor.GetTableMemberName(Expression expression, MobileServiceContractResolver contractResolver)
   at Microsoft.WindowsAzure.MobileServices.Query.FilterBuildingExpressionVisitor.VisitMemberAccess(MemberExpression expression)
   at Microsoft.WindowsAzure.MobileServices.Query.FilterBuildingExpressionVisitor.Visit(Expression node)
   at Microsoft.WindowsAzure.MobileServices.Query.FilterBuildingExpressionVisitor.VisitBinary(BinaryExpression expression)
   at Microsoft.WindowsAzure.MobileServices.Query.FilterBuildingExpressionVisitor.Visit(Expression node)
   at Microsoft.WindowsAzure.MobileServices.Query.FilterBuildingExpressionVisitor.Compile(Expression expression, MobileServiceContractResolver contractResolver)
   at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQueryTranslator1.AddFilter(MethodCallExpression expression)
   at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQueryTranslator1.VisitMethodCall(MethodCallExpression expression)
   at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQueryTranslator1.Visit(Expression expression)
   at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQueryTranslator1.Translate()
   at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQueryProvider.Compile[T](IMobileServiceTableQuery1 query)
   at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQueryProvider.<Execute>d__31.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
   at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQuery1.<ToListAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
   at SocialConnect.Models.Extensions.<FilterByNamedProperty>d__22.MoveNext() in MobileServiceSample\MobileServiceSample\Extensions.cs:line 55`

1 个答案:

答案 0 :(得分:0)

好吧,我终于解决了这个问题。显然问题不在于查询或我正在做的任何事情,而在于SocialBase类。我一直在使用它来创建方法,我知道泛型类型TEntity将具有uuid属性,因此我可以在任何数据库中轻松找到它。但我猜这个字段没有正确序列化,这就是导致NullReferenceException的原因。删除基类后,只是反思地找到属性和值,然后一切都开始正常工作。

我不明白为什么它之前没有正常工作,因为我之前在很多情况下使用了基础SocialBase类。