gpt4 book ai didi

c# - 如何从 DbContext 获取所有 DbSet

转载 作者:太空狗 更新时间:2023-10-29 22:30:23 24 4
gpt4 key购买 nike

我需要使用 EF 获取数据库中的所有表。我需要他们逐张查看并从每个表格中提取某些信息。知道怎么做吗?

最佳答案

这是我在 EntityFramework Plus 库中使用的扩展方法。

using (var ctx = new TestContext())
{
var dbSetProperties = ctx.GetDbSetProperties();
List<object> dbSets = dbSetProperties.Select(x => x.GetValue(ctx, null)).ToList();
}

public static class Extensions
{
public static List<PropertyInfo> GetDbSetProperties(this DbContext context)
{
var dbSetProperties = new List<PropertyInfo>();
var properties = context.GetType().GetProperties();

foreach (var property in properties)
{
var setType = property.PropertyType;

#if EF5 || EF6
var isDbSet = setType.IsGenericType && (typeof (IDbSet<>).IsAssignableFrom(setType.GetGenericTypeDefinition()) || setType.GetInterface(typeof (IDbSet<>).FullName) != null);
#elif EF7
var isDbSet = setType.IsGenericType && (typeof (DbSet<>).IsAssignableFrom(setType.GetGenericTypeDefinition()));
#endif

if (isDbSet)
{
dbSetProperties.Add(property);
}
}

return dbSetProperties;

}
}

编辑您需要使用 DbSet 元素类型的反射并遍历所有属性。这不适用于 TPC、TPT 和 TPH

要获得更简单的解决方案,请使用 Entity Framework Extensions 中的 GetModel 方法。这是该库的一项免费功能。

项目:Entity Framework Extensions

文档:GetModel

免责声明:我是 Entity Framework Extensions 项目的所有者

关于c# - 如何从 DbContext 获取所有 DbSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35207159/

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