簡體   English   中英

實體框架按名稱獲取表

[英]Entity Framework Get Table By Name

我正在尋找通過字符串變量在運行時選擇的表上執行LINQ的方法。

到目前為止,這是我使用反射的內容:

private Entities ctx = new Entities();

public List<AtsPlatform> GetAtsPlatformByName(string atsPlatformName)
{

    List<AtsPlatform> atsPlatform = null;
    System.Reflection.PropertyInfo propertyInfo = ctx.GetType().GetProperty(atsPlatformName.ToLower());
    var platform = propertyInfo.GetValue(ctx, null);

    // it fails here highlighting "platform" with error that reads "Error   1   Could not find an implementation of the query pattern for source type 'System.Data.Objects.ObjectQuery'.  'Select' not found.  Consider explicitly specifying the type of the range variable 'ats'."
    atsPlatform = ((from ats in platform select new AtsPlatform { RequestNumber = ats.RequestNumber, NumberOfFail = ats.NumberOfFail, NumberOfFailWithCR = ats.NumberOfFailWithCR, NumberOfTestCase = ats.NumberOfTestCase }).ToList());         

    return atsPlatform;
}

在我的模型課中,我有:

public class AtsPlatform
{
public string Name { get; set; }
public string RequestNumber { get; set; }
public Int32? NumberOfFail { get; set; }
public Int32? NumberOfTestCase { get; set; }
public Int32? NumberOfFailWithCR { get; set; }
}

在數據庫中,我有以下表格:“ ats1”,“ ats2”,“ ats3” ..“ atsN”,其中每個都有與“ AtsPlatform”中定義的屬性相同的實體字段

我想做的只是:

List<AtsPlatform> a1 = GetAtsPlatformByName("ats1");
List<AtsPlatform> a2 = GetAtsPlatformByName("ats2");
List<AtsPlatform> aN = GetAtsPlatformByName("atsN");

我可以使用“ switch”,但這會使代碼擴展性降低,並且每當創建新的“ ats(N + 1)”時都需要更新。

我的2天研究使我無處可尋,回到零。 我很困。

請幫忙! 謝謝!

而不是反射,如何使用SqlQuery函數?

所以

List<AtsPlatform> GetAtsPlatformByName(int index)
{
    using (var ctx = new Entities())
    {
        return ctx.Database.SqlQuery<AtsPlatform>("SELECT * FROM dbo.ats" + index)
                           .ToList();
    }
}

另外,在數據庫對象上使用SqlQuery方法對實體也沒有更改跟蹤(在我的情況下,這是可以的,因為AtsPlatform類僅包含原始屬性)。

為了進行更改跟蹤,您將需要使用DbSet SqlQuery方法,並且可能需要混入一些反射。

對不起,我的回復很晚,我想嘗試其他解決方案:

解決方案1:主表

正如@Alexw所建議的那樣,只有允許更改數據庫的設計,創建主表才是最好的方法。 我目前正在與數據庫所有者進行更改。 由於依賴關系,此更改必須等到下一階段。

同時,我創建了模擬數據庫來練習這種方法。

解決方案2:原始查詢

正如@Umair所建議的那樣,原始查詢將完成此工作。 我創建了一個處理原始sql查詢的類。

public class AtsRawQuery
{
    private string ConnetionString = "";

    public AtsRawQuery(string connectionString)
    {
        this.ConnetionString = connectionString;
    }

    public List<List<string>> Query(string queryString)
    {
        List<List<string>> results = null;
        MySqlConnection conn = null;
        MySqlDataReader rdr = null;

        try
        {
            conn = new MySqlConnection(this.ConnetionString);
            conn.Open();

            MySqlCommand cmd = new MySqlCommand(queryString, conn);
            rdr = cmd.ExecuteReader();

            if (rdr.HasRows)
            {
                results = new List<List<string>>();
                while (rdr.Read())
                {
                    List<string> curr_result = new List<string>();
                    for (int columnIndex = 0; columnIndex <= rdr.FieldCount - 1; columnIndex++)
                    {
                        curr_result.Add(rdr.GetString(columnIndex));
                    }
                    results.Add(curr_result);
                }
            }
        }
        catch (MySqlException ex)
        {
            Console.WriteLine(ex.Message);
            return null;
        }
        finally
        {
            if (rdr != null)
            {
                rdr.Close();
            }

            if (conn != null)
            {
                conn.Close();
            }

        }
        return results;
    }
}

此類返回一個二維列表供以后使用。

在我的模型類中,我添加了一個解析器方法:

public class AtsPlatform
{
    public string Name { get; set; }
    public string RequestNumber { get; set; }
    public Int32? NumberOfFail { get; set; }
    public Int32? NumberOfTestCase { get; set; }
    public Int32? NumberOfFailWithCR { get; set; }

    public void Parse(string name, string requestNumber, string numberOfFail, string numberOfTestCase, string numberOfFailWithCR)
    {
        Int32 temp;

        this.Name = name;
        this.RequestNumber = requestNumber;
        this.NumberOfFail = (Int32.TryParse(numberOfFail, out temp)) ? Int32.Parse(numberOfFail) : 0;
        this.NumberOfTestCase = (Int32.TryParse(numberOfTestCase, out temp)) ? Int32.Parse(numberOfTestCase) : 0;
        this.NumberOfFailWithCR = (Int32.TryParse(numberOfFailWithCR, out temp)) ? Int32.Parse(numberOfFailWithCR) : 0;
    }
}

解決方案2(b):使用ExecuteStoreCommand進行原始查詢

public List<AtsPlatform> GetAtsPlatformByName(string atsPlatformName)
    {
        List<AtsPlatform> atsPlatforms = null;
        string stm = String.Format("SELECT RequestNumber, NumberOfFail, NumberOfTestCase, NumberOfFailWithCR FROM {0}", atsPlatformName);

        atsPlatforms = new List<AtsPlatform>();
        foreach (AtsPlatform ats in ctx.ExecuteStoreQuery<AtsPlatform>(stm))
            {
                atsPlatforms.Add(ats);
            }

        return atsPlatforms;
    }

解決方案#3:存儲過程

我創建了一個存儲過程,下面是代碼:

DELIMITER $$

CREATE PROCEDURE `UnionAtsTables`()
BEGIN

DECLARE atsName VARCHAR(10);   
DECLARE atsIndex INT; 

SET atsIndex = 1;       
SET @qry = '';

WHILE atsIndex > 0 DO 

    SET atsName =concat('ATS',atsIndex); 
    IF sf_is_table(atsName) = 1 THEN  
        Set @temp_qry = CONCAT('SELECT *, ''', atsName ,''' As TestPlatform FROM ', atsName, ' WHERE RequestNumber <> ''''' );
        If @qry = '' THEN
            SET @qry = @temp_qry;
        ELSE
            SET @qry = CONCAT(@qry, ' UNION ', @temp_qry);
        END IF;
    ELSE  
        SET atsIndex = -1;
    END IF;   

    SET atsIndex = atsIndex + 1;  

END WHILE;  

DROP TABLE IF EXISTS ats_all; 
SET @CreateTempTableQuery = CONCAT('CREATE TEMPORARY TABLE ats_all AS ', @qry ,'');
PREPARE stmt1 FROM @CreateTempTableQuery;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

ALTER TABLE ats_all DROP COLUMN ExecOrder;
ALTER TABLE ats_all ADD ExecOrder INT PRIMARY KEY AUTO_INCREMENT;
ALTER TABLE ats_all auto_increment = 0;

END

這是我在網上找到的用於檢查db中是否存在表的函數。

DELIMITER $$

CREATE FUNCTION `sf_is_table`(`in_table` varchar(255)) RETURNS tinyint(4)
BEGIN 
/** 
* Check if table exists in database in use 
* 
* @name sf_is_table 
* @author Shay Anderson 08.13 <http://www.shayanderson.com> 
* 
* @param in_table (table name to check) 
* @return TINYINT (1 = table exists, 0 = table does not exist) 
*/ 

      # table exists flag 
      DECLARE is_table BOOLEAN DEFAULT FALSE; 

      # table count 
      DECLARE table_count INT DEFAULT 0; 

      # database name 
      SET @db = NULL; 

      # set database name 
      SELECT 
            DATABASE() 
      INTO 
            @db; 

      # check for valid database and table names 
      IF LENGTH(@db) > 0 AND LENGTH(in_table) > 0 THEN 

            # execute query to check if table exists in DB schema 
            SELECT COUNT(1) INTO table_count 
            FROM information_schema.`TABLES` 
            WHERE TABLE_SCHEMA = @db 
                  AND TABLE_NAME = in_table; 

            # set if table exists 
            IF table_count > 0 THEN 
                  SET is_table = TRUE; 
            END IF; 

      END IF; 

      RETURN is_table; 
END

結論:

謝謝大家的建議。 我決定使用解決方案2,因為它對解決方案性能的影響不如解決方案3,並且不需要像解決方案1那樣重新設計數據庫。

我認為您正在做的事情不會像那樣。 您應該基於單個“主”表創建一個實體,例如。 Ats

完成此操作后,您將在Entities類上擁有一個名為Ats的屬性。 現在,您可以使用此屬性通過這樣的原始SQL查詢選擇實體。

var atsName = "ats1";

using (var context = new Entities())
{
    var blogs = context.Ats.SqlQuery(string.Format("SELECT * FROM {0}", atsName)).ToList();
}

或者,您可以嘗試執行此操作(我假設屬性類型為DBSet,因為您未在問題中指定它)

var platform = propertyInfo.GetValue(ctx, null) as DBSet<Ats>;

atsPlatform = platform.Select(ats => new A new AtsPlatform { RequestNumber = ats.RequestNumber, NumberOfFail = ats.NumberOfFail, NumberOfFailWithCR = ats.NumberOfFailWithCR, NumberOfTestCase = ats.NumberOfTestCase }).ToList();     

return atsPlatform;

暫無
暫無

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

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