簡體   English   中英

用於從不同表中獲取記錄的通用查詢

[英]Generic query to get records from different tables

在我們的項目中,我們使用Linq-to-Entities連接到數據庫。 要讀取有效記錄,比方說table1有方法:

public List<tableName> GetTableNameRecords()
{
try
{
    return (from x in _context.tableName
                      where x.valid == 1
                      select x).ToList();
}
catch (Exception ex)
{
    throw new Exception(ex.Message);
}
}

它有效,但有一個問題 - 對於每個表,我們需要編寫相同的查詢,只更改表名。 有沒有辦法編寫通用方法,我們只能傳遞表名? 就像是:

public List<T> GetRecords<T>()
{
try
{
    return (from x in _context.<T>
                      where x.valid == 1
                      select x).ToList();
}
catch (Exception ex)
{
    throw new Exception(ex.Message);
}
}

謝謝你的幫助

你可以使用反射,但你面臨一些相當丑陋的代碼。 但是,如果您願意稍微更改模型,則可以以相對簡單的方式執行此操作。

創建一個具有一個屬性的接口 - valid ,如下所示:

interface IValid
{
    bool valid { get; set; }
}

確保具有此有效字段的所有模型都實現該接口。 然后你可以做這樣的事情:

List<T> GetValid<T>(DbContext context) where T: IValid
{
    return context.Set<T>().Where(x=>x.valid).ToList()
}

通過讓模型實現接口,您可以使用普通的LINQ表達式並讓編譯器對所有內容進行排序。

這是一個使用反射的擴展

    public static IEnumerable<T> GetRecords<T>(this IEnumerable<T> source)
    {
        //check property exists
        var temp = Activator.CreateInstance(typeof(T), new object[] { });
        if (temp.GetType().GetProperty("valid") == null)
            return source;

        return (from item in source
                let table = item.GetType()
                let property = table.GetProperty("valid")
                let value = property.GetValue(item, null)
                where (int)value == 1
                select item).ToList();
    }

用類似的東西來稱呼它

 int count = _context.TableName.GetRecords().Count();

暫無
暫無

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

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