C# Linq SQL 选择要列出的多个列
本文关键字:Linq SQL 选择 | 更新日期: 2023-09-27 18:36:39
嗨,我想从DB中选择4列,然后选择列表
public struct keyData
{
public int pid;
public int sid;
public string proid;
public string title;
}
Entities dbconn = new Entities();
List<keyData> temRes = (
from viewData in dbconn.vw1
join hData in dbconn.tableH
on new { pid= (int)viewData.pid, proid= viewData.proid}
equals new { pid= (int)hData .pid, proid= hData .proid}
into joinSet
from joinUnit in joinSet.DefaultIfEmpty()
where joinUnit == null
select new { pid= (int)viewData.pid, sid= (int)viewData.sid, proid= viewData.proid, Title=viewData.Title }
).ToList();
然后它说:
错误 3 无法隐式转换
type 'System.Collections.Generic.List<AnonymousType#1>'
到'System.Collections.Generic.List<hl.Program.keyData>'
谢谢
使用马尔钦·尤拉谢克的想法
它给了我:
Only parameterless constructors and initializers are supported in LINQ to Entities
这是因为您的 quere 返回了一个匿名类型的对象。将其更改为返回keyData
实例:
List<keyData> temRes = (
from viewData in dbconn.vw1
join hData in dbconn.tableH
on new { pid= (int)viewData.pid, proid= viewData.proid}
equals new { pid= (int)hData .pid, proid= hData .proid}
into joinSet
from joinUnit in joinSet.DefaultIfEmpty()
where joinUnit == null
select new keyData() { pid= (int)viewData.pid, sid= (int)viewData.sid, proid= viewData.proid, Title=viewData.Title }
).ToList();
区别在于select
条款。我在关键字后添加了您的类名new
。
Entities dbconn = new Entities();
List<keyData> temRes = (
from viewData in dbconn.vw1.ToList()
join hData in dbconn.tableH.ToList()
on new { pid= (int)viewData.pid, proid= viewData.proid}
equals new { pid= (int)hData .pid, proid= hData .proid}
into joinSet
from joinUnit in joinSet.DefaultIfEmpty()
where joinUnit == null
select new { pid= (int)viewData.pid, sid= (int)viewData.sid, proid= viewData.proid, Title=viewData.Title }
).ToList();
如前所述,您必须返回keyData
实例而不是匿名类型 https://stackoverflow.com/a/19529805/1034373。但是结构不能有显式的无参数构造函数,因此您必须将 keyData 类型更改为类或添加结构体
public struct keyData
{
public keyData(int pid, int sid, string proid, string title)
{
this.pid = pid;
this.sid = sid;
this.proid = proid;
this.title = title;
}
public int pid;
public int sid;
public string proid;
public string title;
}
并编写这样的代码
List<keyData> temRes = (
from viewData in dbconn.vw1
join hData in dbconn.tableH
on new { pid= (int)viewData.pid, proid= viewData.proid}
equals new { pid= (int)hData .pid, proid= hData .proid}
into joinSet
from joinUnit in joinSet.DefaultIfEmpty()
where joinUnit == null
select new { pid= (int)viewData.pid, sid= (int)viewData.sid, proid= viewData.proid, Title=viewData.Title }
).ToList().Select(x => new keyData(x.pid, x.sid, x.proid, x.title)).ToList();
我在这里回答了类似的问题。你可以简单地使用SELECT和SELECTMANY来做到这一点。https://stackoverflow.com/a/27755340/2764258