LINQ投影关系属性为null [英] LINQ Projecting relation properties with null

查看:75
本文介绍了LINQ投影关系属性为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

无法创建类型为"MyProducer"的空常量值.仅有的 实体类型,枚举类型或原始类型受支持 这种情况.

Unable to create a null constant value of type 'MyProducer'. Only entity types, enumeration types or primitive types are supported in this context.

推荐答案

为什么不使用左联接?

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
    }
}

这篇关于LINQ投影关系属性为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆