I have my class GreenGroup
which inherits from abstract Group
. GreenGroup
has an unmapped property State
that is defined in a partial class.
I have a method GetGreenGroups(GroupFilter filter)
that should return a list of GreenGroup开发者_开发百科 objects where the State == filter.State.
public List<GreenGroup> GetGreenGroups(GroupFilter filter)
{
IQueryable<VirtualMachineInfo> result = GetAllGroupsInternal(userContext);
if(filter.OwnerId != Guid.Empty)
{
result = result.Where(g => g.OwnerID == filter.OwnerId);
}
// this is the unmapped property
if(filter.State.IsNotNullOrEmpty())
{
result = result.Where(g => g.State == filter.State);
}
// This will throw Class Member Unmapped exception
return new List<GreenGroup>(result);
}
However, since State
is not a field in the database, does that mean I cannot include it in my linq query, but would have to further filter my list after the query returns?
I've looked at a few sites including this one in which the user receives the same exception Class Member unmapped
but the field is in their database so it doesn't look like an explicit cast will help me out.
Is my only option to split up the filtering like so?
public List<GreenGroup> GetGreenGroups(GroupFilter filter)
{
IQueryable<VirtualMachineInfo> result = GetAllGroupsInternal(userContext);
if(filter.OwnerId != Guid.Empty)
{
result = result.Where(g => g.OwnerID == filter.OwnerId);
}
var groups = new List<GreenGroup>(result);
if(filter.State.IsNotNullOrEmpty())
{
groups = (from g in groups where g.State == filter.State select g).ToList();
}
return groups;
}
You can use an unmapped field from a partial class in a select clause, but not in a where clause. In the case of the select clause, LINQ to SQL hydrates the entire object and then performs the select projection as necessary. In the case of other clauses (where/order by/etc), the LINQ to SQL engine requires that the columns exist in the database in order to perform the appropriate operation. If you must use the unmapped property in a where clause, you have to force your query from IQueryable to IEnumerable before using the unmapped property. Unfortunately, this requires that the superset be hydrated on the client side and the remainder of the query operation performed client side, which is likely a performance bottleneck. In your example, the final If clause would be something like the following:
IEnumerable<GreenGroup> groups;
if(filter.State.IsNotNullOrEmpty())
groups = (from g in groups.ToEnumerable() where g.State == filter.State select g);
精彩评论