在Entity Framework中获取被忽略的属性

我在EF的框架上工作。 我想获取实体的所有被忽略的属性来构建一些特殊的查询。 我该怎么做?

public class Customer { public int Id { get; set; } public DateTime BirthDate { get; set; } public int Age { get; set; } } public class CustomerContext : DbContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity().Ignore(customer => customer.Age); base.OnModelCreating(modelBuilder); } public DbSet Customers { get; set; } } public static class DbContextExtensions { public static List GetIgnoredProperties(this DbContext context, string entityTypeName) { // ??? } } 

我知道这不是回答你原来的问题,在我的评论中我提到你应该使用反思,但这只是因为我读错了你的问题。

如果你不对,那么这是一个使用reflection的替代方案。

如果将[NotMapped]属性分配给您要忽略的类的属性,则可以使用reflection检索所有[NotMapped]属性。 以下是如何实现这一目标的示例。

 var resultArray = yourClassInstance.GetType().GetProperties() .Where(prop => Attribute.IsDefined(prop, typeof(NotMappedAttribute))); 

希望这能以某种方式帮助你。

您可以通过调用DbModelBuilder.Build来实现所需的function 。 它将在DbModelBuilder的配置设置基础上创建一个DbModelDbModel公开了一个ConceptualModel ,它包含上下文使用的类型。 EdmModel保存在上下文中声明的每种类型,对于每种类型,它保存DbModelBuilder在配置期间未被忽略的属性。 因此,要实现您想要的function,您必须将每个实体类型的属性与EdmModel中的属性相交 。 它将给出它们之间的增量,然后是被忽略的属性。 这是一个例子:

 public class CustomerContext : DbContext { private static IReadOnlyDictionary> _ignoredProperties; /// Hold the ignored properties configured from fluent mapping public static IReadOnlyDictionary> IgnoredProperties { get { return _ignoredProperties; } } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity().Ignore(customer => customer.Age); // Build ignored properties only if they are not if (_ignoredProperties == null) { var model = modelBuilder.Build(this.Database.Connection); var mappedEntityTypes = new Dictionary>(); foreach (var entityType in model.ConceptualModel.EntityTypes) { var type = Type.GetType(entityType.FullName); var typeProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); var mappedProperties = entityType.DeclaredProperties.Select(t => t.Name) .Union(entityType.NavigationProperties.Select(t => t.Name)); mappedEntityTypes.Add(type, new ReadOnlyCollection( typeProperties.Where(t => !mappedProperties.Contains(t.Name)).ToList())); } _ignoredProperties = new ReadOnlyDictionary>(mappedEntityTypes); } base.OnModelCreating(modelBuilder); } public DbSet Customers { get; set; } } 

IgnoreProperties属性是一个单例,将在您第一次使用上下文时进行初始化。 在此之前它将为null,因此必须确保在初始化之前不会使用它。 这是只读的,所以你不必担心意外清除collections品。 实体类型用作键,值显示包含忽略属性的集合。 使用示例:

 var properties = CustomerContext.IgnoredProperties[typeof(Customer)]; 

缺点:

使用这种方法是DbModel将被构建两次,一次用于收集被忽略的属性,第二次是EntityFramework,当DbCompiledModel将被缓存以进行futur ObjectContext创建。 它可以对DbContext的冷启动产生影响,这意味着你第一次对上下文执行查询时,它会慢一点。 它将取决于DbContext的大小。 热烈的询问不应受到影响。 无论如何,OnModelCreating将被调用一次 。

优点:

对de DbModelBuilder配置所做的所有更改都将自动反映在IgnoredProperties属性中。