I供应商类:
public class Supplier {
....
....
....
}
我还有Subcontractor类,Subcontractor是供应商:
public class Subcontractor:Supplier {
....
....
....
}
在我的数据库中,我有带有数据的Suppliers表和另一个带有id字段的表,它作为供应商表的外键,我还有子查询数据。
在实体框架edmx文件中,我声明了继承关系:
现在我想让所有不属于分包商的供应商参与其中:
context.Suppliers.OfType<Supplier>();
但这也会让分包商回归......
我如何才能获得非分包商的供应商?
答案 0 :(得分:5)
尝试一下:
context.Suppliers.Where(s => !(s is Subcontractor));
修改强>
如果你有多个派生自Supplier
的类,LINQ to Entities的唯一选择似乎是:
context.Suppliers.Where(s => !(s is Subcontractor)
&& !(s is DerivedClass2)
&& !(s is DerivedClass3)); // etc.
实体SQL支持ONLY keyword,允许查询特定类型。但是相应的对应物不能用作LINQ运算符。
Here是OfTypeOnly<TEntity>
运算符的一种实现,但它大量使用元数据信息和手动表达式构建,在简单的场景中可能过度。
答案 1 :(得分:1)
我目前使用以下LINQ扩展,假设子类位于同一个程序集中。
public static class MyLinqExtensions
{
public static IQueryable<T> OfTypeOnly<T>(this IQueryable<T> query)
{
Type type = typeof (T);
IEnumerable<Type> derivedTypes = Assembly
.GetAssembly(type)
.GetTypes()
.Where(t => t.IsSubclassOf(type));
return query.ExceptTypes(derivedTypes.ToArray());
}
public static IQueryable<T> ExceptTypes<T>(this IQueryable<T> query, params Type[] excludedTypes)
{
if (excludedTypes == null)
return query;
return excludedTypes.Aggregate(query,
(current, excludedType) => current.Where(entity => entity.GetType() != excludedType));
}
}
用法:
// Get only entities of type Supplier, excluding subclasses.
var suppliers = context.Suppliers.OfTypeOnly<Supplier>();
答案 2 :(得分:-1)
context.Suppliers.Where(s => s.GetType() == typeof(Supplier));