简体   繁体   English

带有别名值的LINQ to Razor View子查询

[英]LINQ to Razor View SubQuery with Alias Value

Background: I have a few tables joined with the following LINQ statement: 背景:我有一些表与以下LINQ语句连接:

var viewModel = new ContractorViewModel();
var Query = (from c in db.Contractors
             join cmb in db.ContractorManagedBies on c.ManagedBy equals cmb.ManagedBy
             join dc in db.DCLocMappings on c.LocationID equals dc.LocationID
             join at in db.AccountTitles on c.AccountTitleID equals at.AccountTitleID
             where dc.DeliveryCenter == location
             select new ContractorViewModel 
             { 
                 Id = cmb.ManagedBy, 
                 FullName = cmb.ManagerFirstName + ' ' + cmb.ManagerLastName 
             }).ToList();

From the first query, the row value is an integer. 从第一个查询开始,行值是一个整数。 I want to also run a parallel LINQ query to join the values of in another table with the values of cmb.ManagerFirstName + ' ' + cmb.ManagerLastName and also show that when the same view is run. 我还想运行一个并行LINQ查询,以将另一个表中的值与cmb.ManagerFirstName + ' ' + cmb.ManagerLastName的值cmb.ManagerFirstName + ' ' + cmb.ManagerLastName并在运行同一视图时显示该值。 I can get most of the details data in the view when placing this at the top of the page: @model IEnumerable<DriverDatabase.Contractor> ;however, I cannot get the value of FullName in the view no matter what I try. 将其放在页面顶部时,可以在视图中获取大多数详细信息数据: @model IEnumerable<DriverDatabase.Contractor> ;但是,无论如何,我都无法在视图中获取FullName的值。 I have tried the ViewModel approach. 我尝试了ViewModel方法。 I thought a subquery would join the table and add the combined first name and last name values in the field from the foreach loop but that isn't the case. 我以为子查询会加入表并在foreach循环的字段中添加组合的名字和姓氏值,但事实并非如此。 My question is, how to get the FullName value to the Razor View using LINQ and ASP.NET 4.5? 我的问题是,如何使用LINQ和ASP.NET 4.5将FullName值获取到Razor View? I am accessing two data sets really but the foreach only recognizes one. 我确实在访问两个数据集,但是foreach只识别一个。 Currently @Html.Display("FullName") does not return anything and there is no object for rendering FullName. 当前, @Html.Display("FullName")不会返回任何内容,也没有用于呈现FullName的对象。

First, I would use double quotes (not single) in concatenation. 首先,我将在连接中使用双引号(而不是单引号)。

FullName = cmb.ManagerFirstName + " " + cmb.ManagerLastName

Then, you should be careful with string concatenation in linq to entities 然后,您应谨慎使用linq中的字符串连接到实体

If first element is null, for example, the whole result will be null. 例如,如果第一个元素为null,则整个结果将为null。

So use a coalesce operator (I think that having it on the left part is enough) 因此,请使用合并运算符(我认为将其放在左侧就足够了)

FullName = cmb.ManagerfirstName ?? string.Empty + " " + cmb.ManagerLastName

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM