Reputation: 471
I am using linq to Entities. I am trying to select a nullable Int
field with below code but I am getting Exception
List<MyClass> myList = myContext.Accounts
.Where(x => x.ACCOUNT_TYPE_ID == 58 && x.IS_DELETED == 0)
.Select(x=> new PayorCode
{
Id = x.ID,
Payor = x.CODE_NUM + " - "+ x.DESCRIPTION
}).ToList();
In Accounts
property CODE_NUM
is of Nullable<global::System.Int32>
.
I am getting the below exception
Unable to cast the type 'System.Nullable`1' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
How should I use the nullable field in Linq to Entites
? I tried with Convert.ToInt32
and object.Equals
but both didn't worked.
Any help will be appreciated
Upvotes: 1
Views: 1621
Reputation: 1
The class list "List" can't be used with the strongly type class list PayorCode referenced in your select. Either use a "var query = ..." along with PayorCode or if List is the same as PayorCode then substitute PayorCode with MyClass. So .Select(x => new MyClass { ....}
Then answer 2 should work fine.
Upvotes: -1
Reputation: 136154
Dealing with nullable ints in EF should be no different to dealing with them under normal circumstances. You can check that they have a value using .HasValue
, you can read the value directly using .Value
and you can null-coalesce using ??
. Depending on what you want to happen in the case that this property is null, you should be able to do something along the lines of:
.Select(x=> new PayorCode
{
Id = x.ID,
Payor = x.CODE_NUM.HasValue
? x.CODE_NUM.Value + " - "+ x.DESCRIPTION
: "CODE_NUM Missing"
})
or perhaps:
.Select(x=> new PayorCode
{
Id = x.ID,
Payor = (x.CODE_NUM ?? "0") + " - "+ x.DESCRIPTION,
})
Upvotes: 3