簡體   English   中英

通過動態調用(獲取)屬性來初始化(實體)object。 實體框架,c#,ASP>NET

[英]Initializing (Entity) object by calling (get) property dynamically. Entity Framework , c#, ASP>NET

我有以下代碼:

public void DBMamLookup(int custid)
{
    using (LookUpEntities1 lookUp = new LookUpEntities1())
    {
        
        var mamconfig = lookUp.MamConfigurations;
        var userlookup = lookUp.UserAccount2_ISO2_3 ;
        
        MamConfiguration obj = mamconfig.Where(m => m.CustID== custid).FirstOrDefault();
        var objNN = lookUp.UserAccount2_ISO2_3.Where(m => m.CustID== custid).Take(15).ToList();            
        
        Type returnType;
        switch (obj.ActiveTableName)
        {
            case "MamConfiguration":
                returnType = typeof(MamConfiguration);
                break;                                            
            case "UserAccount1_ISO1_1Billers":                        
                returnType = typeof(UserAccount1_ISO2_3Billers);
                break;                    
            default:
                returnType = typeof(UserAccount2_ISO2_3Billers);
                break;
        }
        dynamic que3 = this.GetInstance<dynamic>(obj.ActiveTableName);                
        que3 = lookUp.Set(returnType);
        
        for (int i = 0; i < que3.Local.Count; i++)
        {
            Console.WriteLine(que3.Local[i].UserAccount);
        }       
    }
}        

我在上面代碼的下面一行有問題:

var objNN = lookUp.**UserAccount2_ISO2_3**.Where(m => m.CustID== custid).Take(15).ToList(); 

我必須使其動態並在運行時調用特定的實體屬性。 由於我在字符串中有屬性名稱,即 obj.ActiveTableName 我如何進行如下調用:

var objNN = lookUp.**[obj.ActiveTableName]**.Where(m => m.CustID== custid).Take(15).ToList(); 

首先為所有類型創建一個具有通用屬性的接口:例如:

interface IEntityWithCustID
{
    int CustID { get; set; }
}

確保所有相關類都實現該接口例如:

public class UserAccount2_ISO2_3 : IEntityWithCustID

創建幫助程序 class 以檢索數據

static class QueryHelper
{
    public static List<IEntityWithCustID> GetResult(LookUpEntities1 lookup, string tableName, int custId)
    {
        var dbset = lookup.GetType().GetProperty(tableName).GetValue(lookup);
        var entityType = dbset.GetType().GetGenericArguments()[0];
        var method = typeof(QueryHelper).GetMethod(nameof(GetResultInternal)).MakeGenericMethod(entityType);
        return (List<IEntityWithCustID>)method.Invoke(null, new object[] { dbset, custId });
    }

    public static List<IEntityWithCustID> GetResultInternal<T>(IDbSet<T> dbset, int custId) where T: class, IEntityWithCustID
    {
        return dbset.Where(m => m.CustID == custId).Take(15).ToList().Cast<IEntityWithCustID>().ToList();
    }
}

從您的代碼中使用 class (例如)

var res = QueryHelper.GetResult(lookup, obj.ActiveTableName, custid);

還有另一種方法可以創建 Expression.Lambda 以使用 Expression.Lambda 調用創建自定義 lambda 表達式。 不過會稍微復雜一些。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM