简体   繁体   English

DbSet 变量表名

[英]DbSet variable table name

I am writing an application where I need to abstract the DbSet table name.我正在编写一个需要抽象 DbSet 表名的应用程序。 Instead of calling _db.Activities.ToList() (where Activity is a table in Sql) the code below will work for any variable table input.下面的代码不调用_db.Activities.ToList() (其中 Activity 是 Sql 中的表),而是适用于任何变量表输入。

Now I wanted to use .Where(),.OrderBy(),.FromSqlRaw() and other methods on top of the existing code.现在我想在现有代码之上使用.Where()、.OrderBy()、.FromSqlRaw()和其他方法。

How can I write _db.Activities.FromSqlRaw(...) for example, with a variable table name, just like it is doing for the GetAll method.例如,如何使用可变表名编写 _db.Activities.FromSqlRaw(...),就像它为 GetAll 方法所做的那样。

This is my DbSet for Activity这是我的活动 DbSet

public virtual DbSet<Activity> Activities { get; set; } = null!;

This is the method to get all records from a variable table这是从变量表中获取所有记录的方法

public dynamic GetAll(string Table)
        {
            var curEntityPI = _db.GetType().GetProperty(Table);
            var curEntityType = curEntityPI.PropertyType.GetGenericArguments().First();
            // Getting Set<T> method
            var method = _db.GetType().GetMember("Set").Cast<MethodInfo>().Where(x => x.IsGenericMethodDefinition).FirstOrDefault();
            // Making Set<SomeRealCrmObject>() method
            var genericMethod = method.MakeGenericMethod(curEntityType);
            // invoking Setmethod into invokeSet 
            dynamic invokeSet = genericMethod.Invoke(_db, null);
            // invoking ToList method from Set<> invokeSet 
            return Enumerable.ToList(invokeSet); 
        }

The general idea comes from this post总体思路来自这篇文章

reflection-linq-dbset 反射-linq-dbset

Define return type of method as List< dynamic> instead of dynamic将方法的返回类型定义为List<dynamic>而不是dynamic

public List<dynamic> GetAll(string Table)  
{
    //your code...
    return Enumerable.ToList(invokeSet); 
}

Activity Class:活动 Class:

public class Activity
{
    public int Field1 { get; set; }
    public string Field2 { get; set; }
}

So, you can use all methods of List type所以,你可以使用 List 类型的所有方法

var activityList = GetAll("Activities");
var filteredList = activities.Where(x => x.Field1 > 1);
var orderedList = filteredList.OrderBy(x => x.Field2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM