C# 在LINQ查询中获取值
我有一个用于填充网格的查询。这是一个疑问C# 在LINQ查询中获取值,c#,linq,C#,Linq,我有一个用于填充网格的查询。这是一个疑问 var query = from r in DbContext.Groups select new { r.Id, r.Name, r.Description, r.UpdatedBy, r.UpdatedDate, GroupType =DbContext.ProductTypes.Where(p=&g
var query = from r in DbContext.Groups
select
new
{
r.Id, r.Name, r.Description, r.UpdatedBy, r.UpdatedDate,
GroupType =DbContext.ProductTypes.Where(p=>p.Id ==
r.ProductTypes_Id).Select(t=>t.Name)
};
因此,问题是从另一个表中提取的grouptype的值没有显示该值。它正在显示类型(System.Common…)。您能帮我解决这个问题吗?您选择的是顺序而不是项目。如果您知道只返回一个值,请使用
.Single
运算符:
GroupType =DbContext.ProductTypes.Where(p=>p.Id ==
r.ProductTypes_Id).Select(t=>t.Name).Single()
注意末尾添加了.Single()
(它显示类型名称的原因是因为它只是显示了操作符实现类的默认.ToString()
方法。)您是否期望
DbContext.ProductTypes.Where(p=>p.Id==r.ProductTypes\u Id)。选择(t=>t.Name)
返回单个值?现在它看起来像是在分配一个linq匿名类型列表,而不是一个值
如果需要单个值,请使用First或FirstOrDefault(如果可以使用gaurantee或not gaurantee)返回一个值。
.Select(t=>t.Name)
是一个
但是,此代码包含危险的内容,我建议添加额外的检查(例如,如果找不到产品类型,此代码将引发异常等),理想情况下,将此代码移动到存储库或类似的地方。可以尝试
GroupType=DbContext.ProductTypes.Where(p=>p.Id==r.ProductTypes\u Id)。选择(t=>new{name=t.name})
或
GroupType=DbContext.ProductTypes.Where(p=>p.Id==r.ProductTypes\u Id).FirstOrDefault().Name
为什么不使用简单的连接操作
from r in DbContext.Groups join p in DbContext.ProductTypes on r.ProductTypes_Id equals p.Id
select new { Id = r.Id, Name = r.Name, Description = r.Description, UpdatedBy = r.UpdatedBy, UpdatedDate = r.UpdatedDate, GroupType = p.Name };
var query = from r in DbContext.Groups
select
new
{
r.Id, r.Name, r.Description, r.UpdatedBy, r.UpdatedDate,
GroupType =DbContext.ProductTypes.Single(p=>p.Id ==
r.ProductTypes_Id).Name
};
from r in DbContext.Groups join p in DbContext.ProductTypes on r.ProductTypes_Id equals p.Id
select new { Id = r.Id, Name = r.Name, Description = r.Description, UpdatedBy = r.UpdatedBy, UpdatedDate = r.UpdatedDate, GroupType = p.Name };