本文介绍了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

推荐答案

为什么不使用左联接?

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 04:21