c# – 首先从实体框架6数据库中的数据库中获取列名,并在映射中使
发布时间:2020-12-15 23:22:28 所属栏目:百科 来源:网络整理
导读:我遇到的情况是我的表名与使用EF 6中的映射的模型上的类属性不同.模型和数据库如下所示: public class AGENTMap : EntityTypeConfigurationAGENT{ public AGENTMap() { // Primary Key this.HasKey(t = new {t.AgentCode }); // Properties this.Property(t
我遇到的情况是我的表名与使用EF 6中的映射的模型上的类属性不同.模型和数据库如下所示:
public class AGENTMap : EntityTypeConfiguration<AGENT> { public AGENTMap() { // Primary Key this.HasKey(t => new {t.AgentCode }); // Properties this.Property(t => t.AgentCode) .HasMaxLength(10); this.Property(t => t.AgentName) .HasMaxLength(30); // Table & Column Mappings this.ToTable("AGENT"); this.Property(t => t.agent_cd).HasColumnName("agent_cd"); this.Property(t => t.agent_nm).HasColumnName("agent_nm"); } } 这相当于具有这些属性的AGENT类. ObjectContext objectContext = ((IObjectContextAdapter)_context).ObjectContext; ObjectSet<TEntity> objSet = objectContext.CreateObjectSet<TEntity>(); IEnumerable<string> keyNames = objSet.EntitySet.ElementType.KeyMembers .Where(p => p.MetadataProperties.Any(m => m.PropertyKind == PropertyKind.Extended && Convert.ToString(m.Value) == "Identity")) .Select(e => e.Name).ToList(); return keyNames; 它返回Mapping类的Property Name.我想得到“agent_cd”..这是db列名.在EF6中是否有办法在Db上获取确切的列名? 解决方法
Rowan Miller
wrote another blog post准确显示了如何在EF 6中获取列名.
public static string GetColumnName(Type type,string propertyName,DbContext context) { var metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace; // Get the part of the model that contains info about the actual CLR types var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace)); // Get the entity type from the model that maps to the CLR type var entityType = metadata .GetItems<EntityType>(DataSpace.OSpace) .Single(e => objectItemCollection.GetClrType(e) == type); // Get the entity set that uses this entity type var entitySet = metadata .GetItems<EntityContainer>(DataSpace.CSpace) .Single() .EntitySets .Single(s => s.ElementType.Name == entityType.Name); // Find the mapping between conceptual and storage model for this entity set var mapping = metadata.GetItems<EntityContainerMapping>(DataSpace.CSSpace) .Single() .EntitySetMappings .Single(s => s.EntitySet == entitySet); // Find the storage entity set (table) that the entity is mapped var tableEntitySet = mapping .EntityTypeMappings.Single() .Fragments.Single() .StoreEntitySet; // Return the table name from the storage entity set var tableName = tableEntitySet.MetadataProperties["Table"].Value ?? tableEntitySet.Name; // Find the storage property (column) that the property is mapped var columnName = mapping .EntityTypeMappings.Single() .Fragments.Single() .PropertyMappings .OfType<ScalarPropertyMapping>() .Single(m => m.Property.Name == propertyName) .Column .Name; return tableName + "." + columnName; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |