[英]Get the column name from the database in entity framework 6 database first with different property name in mapping
我遇到的情況是我的表名與使用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 寫了另一篇博文 ,詳細介紹了如何在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;
}
可能是這篇文章可以提供幫助。 它們查詢objectContext的MetadataWorkspace
屬性。 http://romiller.com/2012/04/20/what-tables-are-in-my-ef-model-and-my-database/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.