public interface IRepository<T> { IQueryable<T> GetAll(); }
public class LangRepository<T> : IRepository<T> where T : ParentView { private CteDBContext db; publicLangRepository(CteDBContext db) { this.db = db; } public IQueryable<T> GetAll() { var type = typeof(T); if (type == typeof(EnCte)) { var query = db.EnCtes.Cast<T>().AsQueryable(); return query; } if (type == typeof(TwCte)) { var query = db.TwCtes.Cast<T>().AsQueryable(); return query; }
internal class Program { static void Main(string[] args) { try { using (var db = new CteDBContext("DefaultConnection")) { db.Database.Log = e => Console.WriteLine(e); var twRepository = new LangRepository<TwCte>(db); var tws = QueryHelper.Query(twRepository).ToList(); foreach (var tw in tws) { Console.WriteLine(tw.UserName); Console.WriteLine(tw.Id); Console.WriteLine(tw.OrderDate); }
var enRepository = new LangRepository<EnCte>(db); var ens = QueryHelper.Query(enRepository).ToList();
foreach (var en in ens) { Console.WriteLine(en.UserName); Console.WriteLine(en.Id); Console.WriteLine(en.OrderDate); } } } catch (Exception ex) { Console.WriteLine(ex); }
Console.ReadLine(); } }
產出 sql 如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Opened connection at 2023/3/19 上午 12:45:55 +08:00
SELECT [Extent1].[Id] AS [Id], [Extent1].[UserName] AS [UserName], [Extent1].[OrderDate] AS [OrderDate] FROM [dbo].[twcte] AS [Extent1] WHERE ([Extent1].[Id] > 1) AND ((DATEADD(day, cast(0 as float(53)), [Extent1].[OrderDate])) >= @p__linq__0) AND ((DATEADD(day, cast(0 as float(53)), [Extent1].[OrderDate])) < @p__linq__1)
後來發現另外一個方法不過也是很迂迴 , 如果有字串處理需求可能可以考慮用看看 , 需要先安裝這個大神的 lib 接著讓 year , month , day 三個函數實作出來
1 2 3 4 5 6 7 8 9 10 11
public static class BuiltInFunctions { [Function(FunctionType.BuiltInFunction, "Month")] public static int Month(this string value) => Function.CallNotSupported<int>();
[Function(FunctionType.BuiltInFunction, "Year")] public static int Year(this string value) => Function.CallNotSupported<int>();
[Function(FunctionType.BuiltInFunction, "Day")] public static int Day(this string value) => Function.CallNotSupported<int>(); }
public class QueryHelper { public static IQueryable<T> Query<T>(IRepository<T> repository) where T : ParentView { DateTime beginDate = DateTime.Parse("2022-01-05"); DateTime endDate = DateTime.Parse("2022-01-08");
SELECT [Extent1].[Id] AS [Id], [Extent1].[UserName] AS [UserName], [Extent1].[OrderDate] AS [OrderDate] FROM [dbo].[twcte] AS [Extent1] WHERE ( CAST( [Extent1].[OrderDate] AS datetime2) >= @p__linq__0) AND ( CAST( [Extent1].[OrderDate] AS datetime2) < @p__linq__1)