gpt4 book ai didi

c# - 如何在 Entity Framework 中获取表的架构名称?

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

我使用用户模式分离技术来分离数据库中的表。你能告诉我如何在 Entity Framework 中获取 EntitySets(表)的架构名称吗?谢谢。

最佳答案

这现在一定是一个老话题了,但是对于那些仍然潜伏在 EF6+ 中(而不是 EF 核心)的人来说,基于同样优秀的博客 post过去的罗文·米勒 (Rowan Miller),请查看我用于显示有关给定实体的一些元信息的方法

public class DbTableMeta
{
public string Schema { get; set; }

public string Name { get; set; }

public IEnumerable<string> Keys { get; set; }
}


public static DbTableMeta Meta(this DbContext context, Type type)
{
var metadata = ((IObjectContextAdapter) context).ObjectContext.MetadataWorkspace;

// Get the part of the model that contains info about the actual CLR types
var items = (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(p => items.GetClrType(p) == type);

// Get the entity set that uses this entity type
var entitySet = metadata
.GetItems<EntityContainer>(DataSpace.CSpace)
.Single()
.EntitySets
.Single(p => p.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(p => p.EntitySet == entitySet);

// Find the storage entity set (table) that the entity is mapped
var table = mapping
.EntityTypeMappings.Single()
.Fragments.Single()
.StoreEntitySet;

return new DbTableMeta
{
Schema = (string) table.MetadataProperties["Schema"].Value ?? table.Schema,
Name = (string) table.MetadataProperties["Table"].Value ?? table.Name,
Keys = entityType.KeyMembers.Select(p => p.Name),
};
}

关于c# - 如何在 Entity Framework 中获取表的架构名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8770158/

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