nefosfatus
nefosfatus

Reputation: 89

When I use Join I get null

Could you help me with this code?

private readonly MyContext _context;

public FilterLogic(MyContext context)
{
     _context = context;
}

// here I get results
var res = _context.MyTable.AsQueryable().ToList(); 

// here I get null
var result = _context.MyTable.AsQueryable()
                     .Join(_context.SecondTable,
                            p => p.UnicId,   // these columns are equal p.UnicId == c.UnicId
                            c => c.UnicId,
                            (p, c) => new Models.NewTable()); 
var cs = result.ToList();    

I totally misunderstand why it doesn't work. I will be grateful for any help.

Upvotes: 1

Views: 101

Answers (2)

Rena
Rena

Reputation: 36645

As Jeremy Lakeman said, you have not setted the result,so you need to define each row for the newTable.

Here is a simple demo:

1.Model:

public class MyTable
{
    [Key]
    public int UnicId { get; set; }
    public string Name { get; set; }
}
public class SecondTable
{
    [Key]
    public int Id { get; set; }
    public int UnicId { get; set; }
    public string Names { get; set; }
}
public class NewTable
{
    public int UnicId { get; set; }
    public int Id { get; set; }
    public string Name { get; set; }
    public string Names { get; set; }
}

2.Controller:

var result = _context.MyTable.AsQueryable()
            .Join(_context.SecondTable,
                p => p.UnicId,   // these columns are equal p.UnicId == c.UnicId
                c => c.UnicId,
                (p, c) => new Models.NewTable()
                { 
                    Id=p.UnicId,
                    UnicId=p.UnicId,
                    Name=p.Name,
                    Names=c.Names
                });

Upvotes: 1

Jeremy Lakeman
Jeremy Lakeman

Reputation: 11120

This is what you are asking for in your result set;

(p,c) => new Models.NewTable()

So cs will be a List<NewTable> with empty instances for each row of the actual result set. You'll need to define which fields from each table you want returned, or perhaps just an anonymous type containing both objects.

(p,c) => new {Parent = p, Child = c}

However, I'd recommend defining and using navigation properties on the model types, as this is much easier to use.

Upvotes: 2

Related Questions