gpt4 book ai didi

c# - 在映射中首先使用不同的属性名称从 Entity Framework 6 数据库中的数据库中获取列名称

转载 作者:行者123 更新时间:2023-11-30 14:09:36 25 4
gpt4 key购买 nike

我的情况是我的表名与使用 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;

它返回映射类的属性名称。我想获取“agent_cd”..这是数据库列名称..EF6 中是否有一种方法可以获取 Db 上的确切列名称??

最佳答案

罗文·米勒 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;
}

关于c# - 在映射中首先使用不同的属性名称从 Entity Framework 6 数据库中的数据库中获取列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28406810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com