可通过类型<t>处理Null或0值进行查询

时间:2016-07-01 13:58:24

标签: c# entity-framework linq generics

  

{&#34;演员价值类型&#39; System.Int32&#39;失败,因为具体化值为null。结果类型的通用参数或查询必须使用可空类型。&#34;}

我正在尝试使用通用类型null处理可查询列表中的T值。我试过DefaultIfEmpty(0)不起作用,因为无法将Type T转换为int。如何处理nullint s到列表?

public  IEnumerable<T> SelectAll<T>(Object TableName)where T:class
{
    String TableNameString = Type.GetType(TableName.ToString()).Name;
            QueryString = "SELECT" + " " + "*" + " " + "FROM" + " " + TableNameString;
    if (Database.Connection.State == ConnectionState.Closed)
        Database.Connection.Open();

    var a = ((IObjectContextAdapter)this).ObjectContext;
    var t = a.ExecuteStoreQuery<T>(QueryString).AsQueryable().DefaultIfEmpty().ToList();
    List<T> newList = t;
    return newList;
}

1 个答案:

答案 0 :(得分:1)

  

(它)不起作用,因为无法将Type T转换为int

听起来你需要传入类型int?,但由于泛型参数约束,编译器不允许它。你能从你的方法中删除这个约束吗?

where T : class

我不相信DefaultIfEmpty(0)符合您的想法。首先,它在映射失败到T之后才会生效。其次,它不会将null元素替换为0。它将结果集替换为空结果集,其中只有一个值为0的项。

以下是可以为空的映射以及DefaultIfEmpty如何工作的示例。

private void MappingExample()
{
    var complex = GetQuery<ComplexObject>("select Id, null as OptionalAlias from customer").ToArray();
    var simple = GetQuery<int?>("select null as OptionalAlias from customer").ToArray();
}

private void DefaultIfEmptyExample()
{
    var nulls = new int?[] { null, null };
    var nullsWithDefault = simple.DefaultIfEmpty(0); //still full of nulls

    var empty = new int?[] { };
    var emptyWithDefault = empty.DefaultIfEmpty(0); //has one item valued 0
}

private class ComplexObject
{
    public int Id { get; set; }
    public int? OptionalAlias { get; set; }
}

private IEnumerable<T> GetQuery<T>(string sql)
{
    var context = ContextManager.GetNew(); //proprietary, replace with your own
    var parms = new System.Data.SqlClient.SqlParameter[] { };
    return context.Database.SqlQuery<T>(sql, parms);
}