gpt4 book ai didi

c# - 在事先不知道对象类型(类/表)的情况下查询 Entity Framework 实体

转载 作者:太空狗 更新时间:2023-10-29 23:36:26 25 4
gpt4 key购买 nike

我想知道,如果一开始就可能的话,我将如何使用 ID 和表名查询数据库(使用 EF)。

例如,写一个函数为:

QueryDynamicData(string tableName, long entityID){return GetItem(tableName, entityID);}

可以这样称呼:

var entry = QueryDynamicData("Person", 143);

澄清一下,这是针对使用 Entity Framework 的 MVC ASP.Net 项目。

提前致谢!

编辑:

按照@JPVenson 的示例,我想出了以下代码。请注意,它返回一个字典列表,即使 Id 是唯一的,因为我正在考虑何时我们可能想要获取动态表的所有结果,而不仅仅是通过 Id。 (这只是概念证明级别)

public List<Dictionary<string, object>> QueryDynamicData(string table, int entityID)
{
try
{
//Get the table desired based on the table name passed
PropertyInfo dbSetInfo = DBContext.GetType().GetProperties().FirstOrDefault(p => p.Name.ToLower().Equals(table.ToLower()));

//Return all results from the table into IQueryable set where Id = entityID passed
IQueryable anyDbSet = ((IQueryable)dbSetInfo.GetValue(DBContext)).Where("Id=" + entityID);

List<Dictionary<string,object>> listObjects = new List<Dictionary<String, Object>>();

//Iterate through results
foreach (Object entity in anyDbSet)
{
//Create dictionary of Field Name, Field Value from results
Dictionary<string, object> listDBValues = entity.GetType().GetProperties().ToDictionary(propertyInfo => propertyInfo.Name, propertyInfo => propertyInfo.GetValue(entity));

//Add dictionary to list of dictionaries - useful for returning list of found results instead of just one
listObjects.Add(listDBValues);
}

//Return list of dictionaries
return listObjects;
}
catch (Exception e) { }
return null;
}

最佳答案

是的,你可以。有一篇来自 ScottGu 的博客

https://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library

(MS 版本的 DynamicLinq https://github.com/kahanu/System.Linq.Dynamic/wiki)

其中包含名为 DynamicLinq 的库的 wiki。我目前正在一个项目中使用它,它将适合您的方法。

你仍然需要包装它并使用一些反射来构建一个合适的 IQueryable 但它为你做了很多工作

编辑代码示例

经过一些反射(reflection),您可以像这样访问您的 dbSet(未经测试的伪代码!):

public object[] QueryDynamicData(string table, int entityId) {    
//Your DbContext that contains all of your
var dbContext = new FooBaa()
//Get the DbSet in your DbContext that matches the "Table" name.
//You are searching for the generic parameter of the DbSet
var dbSetInfo = dbContext.GetType().GetProperties().FirstOrDefault(e => e.GetGenericArguments().Any(f => f.Name.Equals(table));
//Now get the DbSet from the DbContext and cast it to an IQueryabe
IQueryable anyDbSet = (IQueryable)dbSetInfo.GetValue(dbContext);
//Use Dynamic Linq to create a Query that selects an ID
//warning SQL-Injection possible checkout the 2nd argument of type IDictionary
return anyDbSet.Where("Id=" + entityId).ToArray();
}

关于c# - 在事先不知道对象类型(类/表)的情况下查询 Entity Framework 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46285519/

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