简体   繁体   English

实体框架 | 包括 -> 选择空字段

[英]Entity Framework | Include -> Select Empty Field

I have a problem with our Select.我的 Select 有问题。

But first, we have 3 tables: for example:但首先,我们有 3 个表:例如:

inventory, items, device_properties库存,物品,device_properties

The inventory have Items.库存有项目。 And a few of the Items have device_properties.并且一些项目具有 device_properties。

The items and the device_properties doesnt change. items 和 device_properties 不会改变。 In this case we include fix the device_properties to the items.在这种情况下,我们将 device_properties 修复到项目中。

Now at the call we want to get the inventory, and include at the request an include from items to the inventory entries.现在在调用中我们想要获取库存,并在请求中包含从项目到库存条目的包含。

Now the problem is, if we request it, we send data like x.items.device_properties.name But this can be null.现在的问题是,如果我们请求它,我们会发送像 x.items.device_properties.name 这样的数据,但这可以为空。 And if this is null it doesnt work because:如果这是 null 它不起作用,因为:

nullable object must have a value

and if i do like the following, he needs to long:如果我喜欢以下内容,他需要长篇大论:

deviceName = x.items.device_properties == null ? "" : x.items.device_properties.name
var items = db.inventory.Where(x => x.itemName== itemName).Include(i => i.items).Select(x => new
{
  itemId = x.id,
  x.itemName,
  deviceName = x.items.device_properties.name
}).AsNoTracking().ToList();

At this i get the message, that the nullable needs a value.此时我得到消息,空值需要一个值。 And if i do it like:如果我这样做:

var items = db.inventory.Where(x => x.itemName== itemName).Include(i => i.items).Select(x => new
{
  itemId = x.id,
  x.itemName,
  deviceName = x.items.device_properties == null ? "" : x.items.device_properties.name
}).AsNoTracking().ToList();

The query needs a lot longer查询需要更长的时间

message信息

System.InvalidOperationException: Nullable object must have a value

In addition device_properties should not be null , you should check items property should not be null .此外device_properties不应为null ,您应检查items属性不应为null

var items = db.inventory.Where(x => x.itemName== itemName).Include(i => i.items).Select(x => new
{
  itemId = x.id,
  x.itemName,
  deviceName = x.items == null || x.items.device_properties == null ? "" : x.items.device_properties.name
}).AsNoTracking().ToList();

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

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