2016-01-06 182 views
2

我需要选择数据以在实体框架中填充MVC Asp.net中的DataGrid。当我选择所有值我需要从三个表连接的值:e,类别和产品。连接总是1到0或1.我选择了这个代码的所有walue,但是当没有关联category.name时,我自然有一个例外。做这件事的最好方法是什么?如果在New构造函数中声明,还需要用到其他吗?有条件地Linq新语句选择

var products = from e in dbResult 
          select new 
          { 
           e.Id, 
           e.Title, 
           e.Price, 
           e.Quantity, 
           e.category.nome, 
           e.Product.Sottotitolo, 
           e.Procuct.Provenienza 
          }; 

感谢所有

+0

你得到了什么异常? –

回答

2

此前C#6一个方法是:

var products = from e in dbResult 
          select new 
          { 
           e.Id, 
           e.Title, 
           e.Price, 
           e.Quantity, 
           Noma = e.category == null ? "" : e.category.nome, 
           Sottotitolo = e.Product == null ? "" : e.Product.Sottotitolo, 
           Provenienza = e.Procuct == null ? "" : e.Procuct.Provenienza 
          }; 

用C#6你可以使用?. null-conditional member access操作:

var products = from e in dbResult 
          select new 
          { 
           e.Id, 
           e.Title, 
           e.Price, 
           e.Quantity, 
           Noma = e.category?.nome, 
           Sottotitolo = e.Product?.Sottotitolo, 
           Provenienza = e.Procuct?.Provenienza 
          }; 

注意,后一种方法中的字段值将是null而不是空字符串。