LINQ to Entities Link to Union with Nested Objects

Given the following class structure:

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
}

And the following queries that return users and invitations, respectively, in order to obtain a union of the two queries:

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();

When I try to make the union side of the database, I get a null reference exception in depth in System.Data.Entity.CoreQuery.PlanCompiler. If I call ToList () for each part separately, it works; and if I call ToList () on each part and then combine them, it works.

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

It also seems that if I combine them before creating the ResponseAddress part, create the ResponseAddress part in a later Select call, it works:

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 , - ? , ( , , LINQ .)

+4
2

ResponseAddress ResponseAddress. . , , , ResponseAddress, , .

0

DbSet IDbSet IQueryable, ,    , :

  • foreach (#) (Visual Basic) .
  • , ToArray, ToDictionary ToList.
  • LINQ, First Any, .
  • : DbSet, DbEntityEntry.Reload Database.ExecuteSqlCommand

    var users = db.Users.Select(x => new  
    {
    Id = x.Id,
    Zip = x.Address.Zip
    });

IQueryable , , null

var users = db.Users.Select(x => new  
{
    Id = x.Id,
    Zip = x.Address.Zip
}).ToList();

ToList() db.

0

Source: https://habr.com/ru/post/1622800/


All Articles