简体   繁体   English

LINQ投影关系属性为null

[英]LINQ Projecting relation properties with null

I want to select items from a table, these items have relation properties, can I projecting them if they could be nullable (ie like left join)? 我想从表中选择项目,这些项目具有关联属性,如果它们可以为空(例如,像左联接),可以投影它们吗? And if not how I can workaround this? 如果没有,我该如何解决呢?

class MyProducer
{
  ....
}    

Model model = new Model();
var q = 
    model.Products
    .Select(
      p => 
        new 
        { 
            id = p.Id, 
            producer = p.Producer != null ? new MyProducer { id = p.Producer.Id } : null 
        });

var r = q.ToArray();

When I execute this code I have exception 当我执行此代码时,我有异常

Unable to create a null constant value of type 'MyProducer'. 无法创建类型为“ MyProducer”的空常量值。 Only entity types, enumeration types or primitive types are supported in this context. 在此上下文中仅支持实体类型,枚举类型或原始类型。

Why don't you use left join? 为什么不使用左联接?

using(var model = new Model())
{
    var q = 
    from product in model.Products
    join producer in model.Producers.DefaultIfEmpty()
    on product.ProducerId equals producer.Id
    select new
    {
        Id = product.Id,
        Producer = producer != null ? new MyProducer{ Id = producer.Id} : null
    }
}

Not sure if this is the only way to handle the projection of a possibly null relationship but this is how I have done it in the past. 不知道这是否是处理可能为空的关系的唯一方法,但这是我过去的方法。 You create your new object and then when setting your properties check for null appropriately. 创建新对象,然后在设置属性时适当检查是否为null。 The only problem with this solution is that you now have to check if the 'id' property of 'producer' is '0' to know if the relationship was null. 这种解决方案的唯一问题是,现在您必须检查“生产者”的“ id”属性是否为“ 0”,才能知道该关系是否为空。 If there is a better way of handling this I would love it if someone would post it here. 如果有更好的处理方法,如果有人将其张贴在这里,我会喜欢的。

var q = 
    model.Products
    .Select(p => new 
        { 
            id = p.Id, 
            producer = new MyProducer 
            { 
               id = p.Producer == null ? 0 : p.Producer.Id
            }
        }
     );

var r = q.ToArray();

You need to cast your null to Struct : 您需要将null StructStruct

Model model = new Model(); 
var q = model.Products.Select(p => new { id = p.Id, producer =  
    p.Producer != null ? new Struct { id = p.Producer.Id } : (Struct)null }); 

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

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