Phantom Phantom - 7 days ago 5
C# Question

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:

[DataServiceKey("OrderID")]
public class Order
{
public int OrderID { get; set; }
public int? EmployeeID { get; set; }
// ...other properties...
// ...

public Employee Employees { get; set; }
}


[DataServiceKey("EmployeeID")]
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
Order
class and
Employee
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
_es[o.EmployeeID]
, I have tried every solutions provided in here, but none of them are work for me...I have also tried to use
_es[o.EmployeeID.Value]
, it does solve the error but this time it gaves me
System.InvalidOperationException
error when I run it. Is there any possible solution will be applied to my issue ?

Answer

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;