Sha*_*hay 5 c# linq-to-entities entity-framework-5
My entity NewsItem has a nullable foreign key property: LibraryID of type int?.
My issue is when I query the property and compare it with any value except null, I get exceptions.
Initially my code was:
int? lid = ...
var results = context.NewsItems
.Where(n => n.LibraryID == lid);
Run Code Online (Sandbox Code Playgroud)
but it gives me no results at all, no matter what lid is.
So, I tried:
var results = context.NewsItems
.Where(n => n.LibraryID.Equals(lid));
Run Code Online (Sandbox Code Playgroud)
gives exception:
Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.
and then I tried:
var results = context.NewsItems
.Where(n => lid.Equals(n.LibraryID));
Run Code Online (Sandbox Code Playgroud)
and got:
Unable to cast the type 'System.Nullable`1' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
and this:
var results = context.NewsItems
.Where(n => object.Equals(lid, n.LibraryID));
Run Code Online (Sandbox Code Playgroud)
gives same exception as the last one.
Now I was desperate, so I tried to complicate stuff (like other forums suggested, for example here):
var results = context.NewsItems
.Where(n => (lid == null ? n.LibraryID == null : n.LibraryID == lid));
Run Code Online (Sandbox Code Playgroud)
but still getting same exception.
So... any SIMPLE workarounds?
嗯,第一个片段应该可以工作。我已经多次使用过这样的可空值。我要做的第一件事是进行健全性检查,以确保LibraryID是真实的int?、不是long?或相似的。
除此之外,你还可以尝试这个:
var results = context.NewsItems
.Where(n => (lid.HasValue ? n.LibraryID == lid.Value : !n.LibraryID.HasValue));
Run Code Online (Sandbox Code Playgroud)
或者避免?:在查询中:
var results = lid.HasValue
? context.NewsItems.Where(n => n.LibraryID == lid.Value)
: context.NewsItems.Where(n => !n.LibraryID.HasValue);
Run Code Online (Sandbox Code Playgroud)