I供应商类别:
public class Supplier {
....
....
....
}我也有分包商类和分包商是供应商:
public class Subcontractor:Supplier {
....
....
....
}在我的数据库中,我有一个包含数据的供应者表,另一个包含id字段的表,它是供应者表的外键,我还有减法器数据。
在实体框架edmx文件中,我声明了继承关系:

现在我想要得到所有非分包商的供应商,所以我正在做:
context.Suppliers.OfType<Supplier>();但这也会返回分包商..
如何才能只获取非分包商的供应商?
发布于 2011-05-27 04:53:27
试一试:
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.Entity SQL支持允许查询特定类型的ONLY keyword。但对应的LINQ运算符不可用。
Here是OfTypeOnly<TEntity>运算符的实现,但它大量使用元数据信息和手动表达式构建,在简单的场景中可能会被过度使用。
发布于 2013-12-30 04:51:19
我目前使用以下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>();发布于 2011-05-27 05:27:21
context.Suppliers.Where(s => s.GetType() == typeof(Supplier));https://stackoverflow.com/questions/6144757
复制相似问题