我正在使用LINQ,我想通过传递参数来调用方法(例如checkOpenClose
),并让它返回true
/ false
:
var model = (from account in _ctx.Account
where (...)
select new DetailVM
{
Id = account.Id,
Name = account.CompanyName,
OpenNow = checkOpenClose(account.MonOpen, account.MonClosed,
account.TueOpen, account.TueClosed,
account.WedOpen, account.WedClosed,
account.ThuOpen, account.ThuClosed,
account.FriOpen, account.FriClosed,
account.SatOpen, account.SatClosed,
account.SunOpen, account.SunClosed)
}).Tolist()
我收到以下错误:
LINQ to Entities无法识别方法'Boolean checkOpenClose (System.String,System.String,System.String,System.String, System.String,System.String,System.String,System.String, System.String,System.String,System.String,System.String, System.String,System.String)'方法,而这个方法不可能 翻译成商店表达。
我做错了什么?
答案 0 :(得分:0)
请记住,查询将被转换为sql,因此您的Linq提供程序无法将您的方法调用转换为有效的方法。
如果您确实需要调用该方法,那么我建议调用AsEnumerable
扩展方法,如下所示:
var model= (from account in _ctx.Account
where (...)
select account)
.AsEnumerable()
.Select(account=> new DetailVM
{
Id = account.Id,
Name = account.CompanyName,
OpenNow = checkOpenClose(account.MonOpen, account.MonClosed,
account.TueOpen, account.TueClosed,
account.WedOpen, account.WedClosed,
account.ThuOpen, account.ThuClosed,
account.FriOpen, account.FriClosed,
account.SatOpen, account.SatClosed,
account.SunOpen, account.SunClosed)
})
.Tolist();
这将允许您使用Linq to Objects
执行所需的投影答案 1 :(得分:0)
正如我所见,您正在使用实体框架datacontext,它将linq语句转换为sql脚本,因此当您使用方法时,它无法将其转换为sql。 试试这个
var model= (from account in _ctx.Account
where (...)
select new {
Id = account.Id,
Name = account.CompanyName,
MO = account.MonOpen,
MC = account.MonClosed,
TUO = account.TueOpen,
TUC = account.TueClosed,
WO = account.WedOpen,
WC = account.WedClosed,
THO = account.ThuOpen,
THC = account.ThuClosed,
FO = account.FriOpen,
FC = account.FriClosed,
SO = account.SatOpen,
SC = account.SatClosed,
SUO = account.SunOpen,
SUC = account.SunClosed
}).Tolist().select(m=> new DetailVM {
Id = account.Id,
Name = account.CompanyName,
OpenNow = checkOpenClose(MO,MC,TUO,TUC,WO,WC,THO,THC,FO,FC,SO,SC,SUO,SUC)
}).ToList();
答案 2 :(得分:-1)