we are using entity and I am trying to join 2 tables on 2 columns. an id and server id. My original query didn't account for server (which is what i'm trying to fix)
var client = _Context.Address
.Join(_Context.Clients.Where(c => c.Key == Key),
a => a.AddressId,
c => c.AddressId,
(a, c) => a ).FirstOrDefault();
and this works. But when I add in the server
var client = _Context.Address
.Join(_Context.Clients.Where(c => c.Key == Key),
a => new { a.AddressId, a.ServerId},
c => new { c.AddressId, c.ServerId},
(a, c) => a ).FirstOrDefault();
the join now throws the error in the title. In my research I see that the names and types have to match. The names do match and ive tried assigning them to be doubly sure but that doesn't resolve the issue. Looking at the definition in entity the columns are int in the address table but are nullable int in the client table.
How can I join an int column to an nullable int?
edit: from the client table
public int? AddressId { get; set; }
public int? ServerId { get; set; }
from the address table
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AddressId { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ServerId { get; set; }
CodePudding user response:
How can I join an int column to an nullable int?
You need to make them the same type, otherwise the compiler won't be able to decide what TKey is supposed to be because there isn't an implicit conversion between AnonType<int, int>
and AnonType<int?, int?>
e.g. cast the non-nullable ints to be (int?)
so they match
Join(_Context.Clients.Where(c => c.Key == Key),
a => new { AddressId = (int?)a.AddressId, ServerId = (int?)a.ServerId},
c => new { c.AddressId, c.ServerId},
You got away with it before because there was an implicit conversion from int
to int?
for the single key argument, but it would have similarly errored if you'd used anonymous types with a single prop in your join keys:
//this would fail too
Join(_Context.Clients.Where(c => c.Key == Key),
a => new { AddressId },
c => new { c.AddressId },