我在返回列表时遇到问题, 这是我的代码:
public List<tblLaborBankAccount> ListAllLaborBankAccountByLaborID (int laborID)
{
var result = (from b in context.tblBankNames
join c in context.tblLaborBankAccounts
on b.bknBankNameID equals c.bknBankNameID
where c.lbrLaborID == laborID
select (new { c, b })
).ToList();
return result;
}
并且 result
返回一个匿名类型,因为我正在返回一个连接查询并且返回类型不再是 tblLaborBankAccount
。
我应该为这个匿名类型创建一个新类还是有更好的方法?
谢谢。
最佳答案
select 语句是一个创建匿名类的投影。
匿名类可以在方法中使用,但不能作为结果返回。
你可以返回一个 List<Tuple<tblBankName, tblLaborBankAccount>>
像这样:
public List<Tuple<tblBankName, tblLaborBankAccount>> ListAllLaborBankAccountByLaborID (int laborID)
{
var result = (from b in context.tblBankNames
join c in context.tblLaborBankAccounts
on b.bknBankNameID equals c.bknBankNameID
where c.lbrLaborID == laborID
select (new Tuple<tblBankName, tblLaborBankAccount>( c, b ))
).ToList();
return result;
}
或者您可以声明一个结构/类来包含您的结果:
public class BankAccountDetails
{
public tblBankName BankName {get;set;}
public tblLaborBankAccount BankAccount {get;set;}
}
然后返回它们的列表:
public List<BankAccountDetails> ListAllLaborBankAccountByLaborID (int laborID)
{
var result = (from b in context.tblBankNames
join c in context.tblLaborBankAccounts
on b.bknBankNameID equals c.bknBankNameID
where c.lbrLaborID == laborID
select (new BankAccountDetails{ BankName = c, BankAccount = b })
).ToList();
return result;
}
关于c# - 无法将类型 'System.Collections.Generic.List<AnonymousType#1>' 隐式转换为 'System.Collections.Generic.List<Model.tblLaborBankAccount>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25339337/