我想通过下面的LINQ查询向ViewBag返回一个值
var myCompanyName = (from c in db.Companies
where c.CompanyId == CompanyID
select c.CompanyName).ToString();
ViewBag.myCompanyName = myCompanyName;
在我的MVC控制器中,但我在视图中得到以下输出。
SELECT [Extent1].[CompanyName] AS [CompanyName] FROM [dbo].[Companies] AS [Extent1] WHERE [Extent1].[CompanyId] = @p__linq__0 Company Name from Controller Action
View Bag预期的结果应该是:CompanyName XYZ。请问我该如何做到这一点?
答案 0 :(得分:3)
您没有实现查询,我怀疑您想要返回单个值(而非IEnumerable<string>
),因此您需要将.ToString()
替换为.FirstOrDefault()
var myCompanyName = (from c in db.Companies
where c.CompanyId == CompanyID
select c.CompanyName).FirstOrDefault();
ViewBag.myCompanyName = myCompanyName;
或者如果您确实想要一个string
的集合,那么它将是.ToList()