Phantom Phantom - 1 month ago 5x
ASP.NET (C#) Question

LINQ - Cannot convert from ' int? ' to ' int ', same variable name in different class but one is nullable

I have the following classes which have the same variable, but one of them is nullable, the other one is not because it is a primary key in that table:

public class Order
public int OrderID { get; set; }
public int? EmployeeID { get; set; }
// ...other properties...
// ...

public Employee Employees { get; set; }

public class Employee
public int EmployeeID { get; set; }
// ...other properties...
// ...

public IEnumerable<Order> Orders { get; set; }

The general idea between these 2 classes is an order can belong to 1 Employee, but there might also exist an order that is not assigned to any Employee yet, an Employee must have at least 1 order or more than 1. Now I am trying to create an association between
class and
class, and this is how I did:

// Create an association between Orders and Employees
var _es = _Employees.ToDictionary(e => e.EmployeeID);
var _os = _Orders.ToLookup(o => o.EmployeeID);
foreach (var o in _Orders) o.Employees = _es[o.EmployeeID];
foreach (var e in _Employees) e.Orders = _os[e.EmployeeID];

I got
cannot convert from "int?" to "int"
error in
, I have tried every solutions provided in here, but none of them are work for me...I have also tried to use
, it does solve the error but this time it gaves me
error when I run it. Is there any possible solution will be applied to my issue ?


You're passing an int? for a key to a dictionary where int is needed.

o.Employee is an int?.

es is a Dictionary<int, Employee>.

You probably want:

o.Employees = o.EmployeeID != null ? _es[o.EmployeeID] : null;