【发布时间】:2017-07-13 08:39:31
【问题描述】:
这只是从 Cars 中选择的一些列:
var qs = myDataContext.Cars
.Select(c => new { c.id, c.color })
.ToList();
我需要的是功能,它会做同样的事情,但是通过 SqlCommand,所以我可以改变这个过程。它的(简化的)代码在这里
public static IEnumerable<P> ProjectionFunction<T, P>(
this System.Data.Linq.Table<T> input,
Func<T, P> projection
) where T : class
{
System.Data.Linq.DataContext dc = input.Context;
string paramList = string.Join(
",",
typeof(P).GetProperties().Select(s => s.Name)
);
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(
"SELECT " + paramList + " FROM " + typeof(T).Name,
(System.Data.SqlClient.SqlConnection)dc.Connection
);
cmd.CommandType = CommandType.Text;
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
return dc.Translate<P>(cmd.ExecuteReader()); // <-- the problem is here
}
该函数适用于像这样的普通类
private class X
{
public int? id { get; set; }
public string color { get; set; }
}
var qx = myDataContext.Cars
.ProjectionFunction(c => new X () { id = c.id, color = c.color })
.ToList();
但它在匿名类型上失败
var qa = myDataContext.Cars
.ProjectionFunction(c => new { c.id, c.color })
.ToList();
我得到运行时错误
类型 f__AnonymousType20`2[System.Nullable`1[System.Int32],System.String] 必须声明一个默认(无参数)构造函数才能成为 在映射期间构建。
用于Translate<> 函数。我试过的ExecuteQuery<> 也是如此。很难相信 DataContext 不知道如何构建匿名类型,这是他一直在做的事情。我错过了什么?我怎样才能让他为我这样做?
单独使用一个类的问题在于,它的属性必须与原始类的属性的类型和名称显式同步,这使得这种方法有些不切实际。
【问题讨论】:
标签: c# linq linq-to-sql projection anonymous-types