Using reflection to address a Linqed property

后端 未结 3 2044
青春惊慌失措
青春惊慌失措 2021-01-03 17:22

I\'m trying to writing a generic method that will load a record of a specific type, with a specific ID. Here\'s one way that works:

    public abstract clas         


        
3条回答
  •  心在旅途
    2021-01-03 18:03

    Having read these posts: Generic Data Access using LINQ to SQL and C#, LINQ-to-SQL: Generic Primary Key function and Calling a generic method with Type

    My colleague and I came up with the following digest:

    We added the following method to our datacontext (in a partial class).

    public T GetInstanceByPrimaryKey(object primaryKeyValue) where T : class
    {
        var table = this.GetTable();
        var mapping = this.Mapping.GetTable(typeof(T));
        var pkfield = mapping.RowType.DataMembers.SingleOrDefault(d => d.IsPrimaryKey);
    
        if (pkfield == null)
            throw new Exception(String.Format("Table {0} does not contain a Primary Key field", mapping.TableName));
    
        var param = Expression.Parameter(typeof(T), "e");
    
        var predicate =
            Expression.Lambda>(Expression.Equal(Expression.Property(param, pkfield.Name), Expression.Constant(primaryKeyValue)), param);
    
        return table.SingleOrDefault(predicate);
    }
    

    Then, where we need to instanciate from the type name and primary key value:

    string name = "LinqObjectName";
    int primaryKey = 123;
    
    var dc = new YourDataContext();
    
    Type dcType = dc.GetType();
    Type type = dcType.Assembly.GetType(String.Format("{0}.{1}", dcType.Namespace, name));
    
    MethodInfo methodInfoOfMethodToExcute = dc.GetType().GetMethod("GetInstanceByPrimaryKey");
    MethodInfo methodInfoOfTypeToGet = methodInfoOfMethodToExcute.MakeGenericMethod(name);
    var instance = methodInfoOfTypeToGet.Invoke(dc, new object[] { primaryKey });
    
    return instance;
    

    Hope this helps!

提交回复
热议问题