I have this code:
var item = (from se in _db.Events
where se.ID == id
select new PseudoEvent()
{
ID = se.ID,
categoryId = se.Categories.ID,
}).FirstOrDefault();
The "Events" and "Categories" tables have a relationship:
"Events" table > Category_ID = "Categories" table > ID
When i dont select a category for the event the "Category_ID" in the "Events" table stays "NULL" and in my code above i get this error:
The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type
How can i fix that so the event item will be shown even if the Category_ID column is null?
Please advise
Thanks
Loading
Sanjeeb LenkaPosted Oct 17, 2013, 6:36 AM
var item = (from se in _db.Events
where se.ID == id
select new PseudoEvent()
{
ID = se.ID,
categoryId = (se.CategoriesID== null) ? 0 : se.CategoriesID };
}).FirstOrDefault();
here if catagoryid come as null it will assign 0 to it.
navePosted Oct 20, 2013, 4:33 AM
I have another question related to this issue:
How do i update the Category_ID column back to null?
On insert or update i use this:
getCategory = _db.Categories.Find(id);
Events.Categories = getCategory; //add foreign key
But if the category is 0 (not selected) i want to update the relationship Category_ID back to null.
Try to do it like that:
Events.Categories = null; //add foreign key
But it doesn't seems to work
Please advise
Thanks