How do I filter certaing condition on a specific subtype of an inherited entity object in a query?
I have three tables in my SQL 2008 database: User, CutomerUser and SalesUser. They represent different type of users. In my conceptual model these are modelled so that CustomerUser and SalesUser entities are inherited from User. On the database level CustomerUser and SalesUser have their primary key that are at the same time a foreign key into User. Thus the relationship is one to zero or开发者_运维问答 one.
CustomerUser table has a CustomerNumber column and SalesUser table has a RepresentativeCode column. I want to write a query that return whatever Users, CustomerUsers or SalesUsers are there based on a selection criteria. Please note that there are Users that neither CustomerUsers nor SalesUsers.
I want no return all users that have their login equals to specified string regardless of type. In additions if the a CustomerUser has customer number equals to the specified string I want to return it, and similarily I want to return SalesUsers that have representative code equals to the string specified.
I write the following query:
var users = from u in Context.Users
where (((u is CustomerUser) && ((CustomerUser)u).CustomerNumber.Equals(criteria))
|| ((u is SalesUser) && ((SalesUser)u).RepresentativeCode.Equals(criteria)))
|| u.Login.Equals(criteria)
select u;
The query compiles, but in runtime when the query gets executed, the following exception is thrown:
"Unable to cast the type 'MyDb.Models.User' to type 'MyDb.Models.CustomerUser'. LINQ to Entities only supports casting Entity Data Model primitive types."
How do I write my query so it works?
NOTE: I'm going to apply sorting/paging to the query down the pipeline, so doing ToList() and then casting kind of solution won't work for me here.
You have to use as
casts. You can also take advantage of the fact that L2E coalesces nulls:
var users = from u in Context.Users
let customerNumber = (u as CustomerUser).CustomerNumber
let representativeCode = (u as SalesUser).RepresentativeCode
where customerNumber.Equals(criteria)
|| representativeCode.Equals(criteria)
|| u.Login.Equals(criteria)
select u;
精彩评论