加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – LINQ to Entities对带有嵌套对象的Union的null引用

发布时间:2020-12-15 20:57:32 所属栏目:百科 来源:网络整理
导读:给定以下类结构: public class User // DB model{ public Guid Id { get; set; } public Address Address { get; set; } // And other propeties}public class Invitation // DB model{ public Guid Id { get; set; } // And other propeties}public class
给定以下类结构:

public class User  // DB model
{
    public Guid Id { get; set; }
    public Address Address { get; set; }
    // And other propeties
}

public class Invitation  // DB model
{
    public Guid Id { get; set; }
    // And other propeties
}

public class Address  // DB model
{
    public string Zip { get; set; }
    // And other properties
}

public class ResponseModel
{
    public Guid Id { get; set; }
    public ResponseAddress Address { get; set; }
}

public class ResponseAddress
{
    public string Zip { get; set; }
    // And other properties
}

以下查询分别返回用户和邀请,目的是获得两个查询的并集:

var users = db.Users.Select(x => new ResponseModel() 
{
    Id = x.Id,Address = new ResponseAddress()
    {
        Zip = x.Address.Zip
    }
});
var invitations = db.Invitations.Select(x => new ResponseModel() 
{
    Id = x.Id,Address = new ResponseAddress()
    {
        Zip = String.Empty
    }
});
var union = users.Union(invitations).ToList();

当我尝试使用union DB-side时,我在System.Data.Entity.CoreQuery.PlanCompiler中深入获得了一个null引用异常.如果我单独调用每个部件上的ToList(),它就可以工作;如果我在每个部分上调用ToList()然后将它们联合起来,它就可以了.

users.ToList();
invitations.ToList();
users.ToList().Union(invitations.ToList());

看来如果我在创建ResponseAddress部分之前将它们联合起来,那么在稍后调用Select时创建ResponseAddress部分,它可以工作:

var users = db.Users.Select(x => new  
{
    Id = x.Id,Zip = x.Address.Zip
});
var invitations = db.Invitations.Select(x => new  
{
    Id = x.Id,Zip = String.Empty
});
var union = users.Union(invitations).Select(x=>new ResponseModel() {
    Id = x.Id,Address = new ResponseAddress() {
        Zip = x.Zip
    }
}).ToList();

关于为什么在第一组查询中调用Union会返回空引用异常的任何想法,而最后一个查询中的调用不会?两者都在DB端执行,两者都应该产生类似的查询(理论上几乎相同,除了LINQ查询嵌套的方式.)

解决方法

在ResponseAddress部分中,您将创建一个ResponseAddress类的新实例.这对关系数据库没有意义.当您将查询结果转换为列表时,它是运行时处理联合的工作,它知道对象,而数据库服务器不知道ResponseAddress,因为它不是它如何表示数据.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读