假設我有一個字串串列,表示使用 SQL Server 的物體框架生成的類的名稱:
public static List<string> tableList = new List<string>
{
"aaa",
"bbb",
"ccc",
"ddd",
"eee",
};
我想從物體加載資料:
DateTime from_date = DateTime.MinValue;
DateTime to_date = DateTime.MaxValue;
using (var ctx = new MyEntities())
{
IList<aaa> aa = ctx.aaa
.Where(a => a.date_added >= from_date &&
a.date_added <= to_date)
.ToList();
}
但我必須用 20 個或更多的桌子來做這件事。
有沒有辦法讓我動態地做到這一點?喜歡:
Result res = new Result();
List<Result> r = new List<>();
foreach (string table in tableList)
{
using (var ctx = new MyEntities())
{
IList<*table*> aa = ctx.*table*
.Where(a => a.date_added >= from_date &&
a.date_added <= to_date)
.ToList();
res.quantity = aa.Count();
res.title = table;
}
r.Add(res);
}
所有需要的表都有列date_added。
PS:我只需要計算在定義的時間段內每個表中有多少行。像表客戶、客戶、員工:從 2020 年到 2021 年注冊了多少。我將輸出:
{
"title":"Client",
"quantity": 19,
"from_date": [some_date],
"to_date": [some_date]
},
{
"title":"Customer",
"quantity": 123,
"from_date": [some_date],
"to_date": [some_date]
},
{
"title":"Employee",
"quantity": 31,
"from_date": [some_date],
"to_date": [some_date]
},
uj5u.com熱心網友回復:
考慮到您對我的評論的回答,您可以將類添加到由 EF 生成類的命名空間。我建議您在該名稱空間中創建一個新介面,如下所示:
public interface IObjectWithDates
{
DateTime date_added { get; }
}
現在我們希望生成的類具有 date_added 欄位來實作 IObjectWithDates 介面。您可以在同一個命名空間中添加一個附加檔案,而不是修改生成的類
public partial class Client: IObjectWithDates
{ }
public partial class Customer: IObjectWithDates
{ }
//and so on with the classes you want to track
現在我們有了一個包含一些實作 IObjectWithDates 的類的程式集。Type t = Type.GetType(...)如果你愿意的話,你可以用它們的名字來獲取這些類。您還可以要求 C# 為您提供在模型命名空間中實作 IObjectWithDates 的所有類:
public IEnumerable<Type> AllTrackedClassesInNameSpace(string namespaceName, Assembly assembly)
{
return assembly.GetTypes()
.Where(x => ((!string.IsNullOrWhiteSpace(x.Namespace)) && (x.Namespace.ToUpper().Contains(namespaceName.ToUpper()))))
.Where(x => x.IsClass)
.Where(x=>typeof(IObjectWithDates).IsAssignableFrom(x));
}
[
在這里編輯]此時,您將擁有一個型別串列(IEnumerable<Type> typeList在以下代碼中),所有型別都實作了 IObjectWithDates 并且您應該能夠做到這一點:
public int MyCount<T>(DbContext ctx) where T: class, IObjectWithDates
{
return ctx.Set<T>().Count(a => a.date_added >= from_date && a.date_added <= to_date);
}
接著
Result res = new Result();
List<Result> r = new List<Result>();
using (var ctx = new DbContext(""))
{
foreach (var type in typeList)
{
var method = this.GetType().GetMethod("MyCount").MakeGenericMethod(type);
res.quantity = (int)method.Invoke(this, new object[]{ ctx });
res.title = table;
}
r.Add(res);
}
一些細節可能需要調整(例如 from_date / to_date 可以是 MyCount 的引數或呼叫類的屬性),但全域的想法是存在的。您可以通過反射在背景關系中獲取 Set<>() 方法,但在我看來,單獨的方法更易于閱讀和除錯。
請注意,生成 IList<> 物件只是為了計算它們是不明智的,因為 SQL 將請求所有物件,然后 EF 將在每行上實體化很多實體......只是為了計算它們而不是使用 Select Count...
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/406364.html
標籤:
