使用实体框架6我可以通过Fluent Api像这样设置配置:
Using Entity-Framework 6 I'm able to set up the configuration through Fluent Api like this:
public class ApplicationUserConfiguration : EntityTypeConfiguration<ApplicationUser> { public ApplicationUserConfiguration() { this.HasKey(d => d.Id); this.Ignore(d => d.UserId); } }源于此问题
使用属性方法,我能够通过反射知道什么是属性角色,但我想知道如何使用Fluent Api方法检索这些配置,例如Key?
Using the attribute approach I'm able to know what's the property roles by reflection, but I wonder how can I retrieve these configurations, like Key for example, with Fluent Api approach?
EntityTypeConfiguration<>类没有公共属性.
是否可以通过某种方式获得Key和ForeignKey?
Is that possible to get the Key and ForeignKey somehow?
推荐答案有一个 MetadataWorkspace 类,该类提供API来检索有关存储,模型,CLR类型和映射的元数据实体框架.
There is a MetadataWorkspace class which provides API to retrieve metadata about storage, model, CLR types and mappings for Entity Framework.
代表ADO.NET元数据运行时服务组件,该组件 为从各种来源检索元数据提供支持.
Represents the ADO.NET metadata runtime service component that provides support for retrieving metadata from various sources.
具有DbContext的实例,可以使用以下代码找到其MetadataWorkspace:
Having an instance of DbContext, you can find its MetadataWorkspace using following code:
var metadataWorkspace = ((IObjectContextAdapter)dbContext).ObjectContext.MetadataWorkspace;然后,您将获得包含不同类型的模型的项目集合,这些模型包括对象模型,概念模型,存储(数据库)模型以及概念模型和存储模型之间的映射模型.
Then you can get item collections which contain different types of models including object model, the conceptual model, the storage (database) model, and the mapping model between the conceptual and storage models.
以下扩展方法返回 EntityType 对于给定的clr类型:
The following extension methods returns EntityType for given clr type:
using System; using System.Data.Entity; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Infrastructure; using System.Linq; public static class DbContextExtensions { public static EntityType GetEntityMetadata<TEntity>(this DbContext dbContext) { if (dbContext == null) throw new ArgumentNullException(nameof(dbContext)); var metadataWorkspace = ((IObjectContextAdapter)dbContext) .ObjectContext.MetadataWorkspace; var itemCollection = ((ObjectItemCollection)metadataWorkspace .GetItemCollection(DataSpace.OSpace)); var entityType = metadataWorkspace.GetItems<EntityType>(DataSpace.OSpace) .Where(e => itemCollection.GetClrType(e) == typeof(TEntity)).FirstOrDefault(); if (entityType == null) throw new Exception($"No entity mapped to CLR type '{typeof(TEntity)}'."); return entityType; } }然后,您可以使用EntityType提取有关模型的更多信息,例如,您可以找到一个关键属性列表:
Then you can use EntityType to extract more information about the model, for example you can find a list of key properties:
var keys = dbcontext.GetEntityMetadata<Category>().KeyProperties.Select(x=>x.Name).ToList();更多推荐
如何从Fluent Api检索实体配置
发布评论