2015-06-15 58 views
1

任何方式傳遞表名作爲參數,並用make廣義函數從數據庫獲取記錄我們可以通過傳遞表值來調用實體框架查詢嗎?

string table = "tbl_Category"; 
int Id = Class.getLastId(table); 

Class.aspx

public static int getLastId(string table) 
    { 

     int lastID = 0; 
     using (HatnEntities context = new HatnEntities()) 
     { 
      // Fetch Id of last record from table 
       var result = (from c in context.tbl_Category.OrderByDescending(u => u.Id) select new { Id = c.Id }).FirstOrDefault(); 
               ^
//any way to use table name from parameter value"+table+" 


       if (result != null) 
       { 
        lastID = Convert.ToInt32(result.Id); 
       } 
       obj.Id = lastID + 1; 
       context.tbl_Category.Add(obj); 
       context.SaveChanges(); 

     } 
     return status; 
    } 

請讓我知道是否有可能

回答

0

您可以使用Set(),它需要傳遞您的表字符串參數,您必須從您的程序集中獲取Type。

context.Set<TypeFromTableStringParameter>() ... 
0

這是你必須做什麼,如果你只是希望能夠訪問EF任何表:

public static int getLastId<T>() 
    where T : PrimaryKey 
{ 
    using (HatnEntities context = new HatnEntities()) 
    { 
     // Fetch Id of last record from table 
     var result = (from c in context.Set<T>().OrderByDescending(u => u.Id) select new { Id = c.Id }).FirstOrDefault(); 

     var lastID = 0; 
     if (result != null) 
     { 
      lastID = Convert.ToInt32(result.Id); 
     } 
     obj.Id = lastID + 1; 
     context.Set<T>().Add(obj); 
     context.SaveChanges(); 
    } 

    // not sure where this comes from? 
    return status; 
} 

public abstract class PrimaryKey 
{ 
    public int Id { get; set; } 
} 

你們所有的實體將需要繼承(擴展)PrimaryKey爲了您可以根據Id的屬性SelectWhereFirstOrDefault(等等)。

相關問題