繁体   English   中英

LINQ DefaultIfEmpty(),生成推断的参数错误

[英]LINQ DefaultIfEmpty(), generating inferred argument error

我试图让下面的linq查询返回-1如果没有任何当前值。 我正看着这篇文章在MSDN上, 在这里 ,它似乎DefaultIfEmpty()是我想要的。

不幸的是,我得到的是The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly. The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly. 错误。

我想我不确定这意味着什么或告诉我要做什么。 有人可以解释一下。

 public static int CheckForDRIID(int personID)
    {
        using (var context = ConnectDataContext.Create())
        {
            var masterIndex =
                (from applicationAssociation in context.tblApplicationAssociations
                 where applicationAssociation.ApplicationID == 1 && applicationAssociation.PersonID == personID
                 select applicationAssociation.PersonApplicationID).DefaultIfEmpty(-1).Single();


            return Convert.ToInt32(masterIndex);
        }
    }

-1是一个int,而applicationAssociation.PersionApplicationID不是,因此它不知道返回什么。 您可以将-1替换为与applicationAssociation.PersionApplicationID “ -1”相同的类型。 或指定类似DefaultIfEmpty<string>的类型。 第三个选项是在选择中执行Convert.ToInt32

该代码对我来说很好:

public static int CheckForDRIID(int personID)
{
    var someAssociaction = new { ApplicationID = 1, PersonID = 1, PersonApplicationID = 1 };
    var associactions = (new[] { someAssociaction }).ToList();
    associactions.Add(new { ApplicationID = 2, PersonID = 2, PersonApplicationID = 2 });

    int masterIndex =
        (from applicationAssociation in associactions
         where applicationAssociation.ApplicationID == 1 && applicationAssociation.PersonID == personID
         select applicationAssociation.PersonApplicationID).DefaultIfEmpty(-1).Single();

    return masterIndex;
}

我刚刚创建了一个关联示例集,因为我没有您的数据上下文。 顺便说一句:您可以将masterIndex声明为int ,因为您知道表达式将返回的类型,所以您不需要var

因此,导致问题的原因在其他地方: PersonApplicationID字段不是int ,因此编译器不知道应该为通用函数DefaultIfEmpty推断哪种类型。

更新:刚刚尝试通过将PersonApplicationID属性设置为PersonApplicationID示例:

  • new Nullable<int>(1) :抛出“无法隐式转换类型'int?' 到“ int””
  • 1f :引发“无法将类型'float'隐式转换为'int'”
  • "" :引发“无法从用法中推断出方法DefaultIfEmpty<TSource>的类型参数。尝试显式指定类型参数。”

因此,我假设您将字符串存储在数据库的PersonApplicationID字段中。 如果是这样,请更改您的数据库,或在Linq查询中将字符串解析为int:

public static int CheckForDRIID(int personID)
{
    using (var context = ConnectDataContext.Create())
    {
        int masterIndex =
            (from applicationAssociation in context.tblApplicationAssociations
             where applicationAssociation.ApplicationID == 1 && applicationAssociation.PersonID == personID
             select int.Parse(applicationAssociation.PersonApplicationID)).DefaultIfEmpty(-1).Single();

        return masterIndex;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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