3

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 ?

1
  • 2
    you can try like this foreach (var o in _Orders) o.Employees = _es[o.EmployeeID] ?? Default(int); Commented Sep 9, 2016 at 5:02

2 Answers 2

3

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; 
Sign up to request clarification or add additional context in comments.

3 Comments

Instead of checking null, check whether it has value using HasValue
@BalagurunathanMarimuthu checking for null is the way most idiomatic to C#. It is syntax sugar for HasValue -- the two are identical.
Yes, I agree.. but Nullable variable contains predefined property to check whether the variable has value or null.
1

Check HasValue before assign the value.

foreach (var o in _Orders) { if (_es[o.EmployeeID].HasValue) { o.Employees = _es[o.EmployeeID]; } } 

or

foreach (var o in _Orders) o.Employees = _es[o.EmployeeID].HasValue ? _es[o.EmployeeID] : null; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.