2012-10-22 54 views
1

我想創建一個通用的方法,根據給定的參數,如:table,field1和field2從Linq獲取數據。一般Linq數據方法

一個方法,將改爲使用這些2分特異性的人。例如:

public void DistributeCB(ComboBox cb) 
    { 
     BooksDBDataContext db = new BooksDBDataContext(); 
     Type T = db.GetType(); 

     //Authors table 
     var data =db.Authors.Select(author => new 
     { 
      Id = author.AuthorId, //field 1 
      Value = author.AuthorName //field 2 
     }); 
     cb.ValueMember = "Id"; 
     cb.DisplayMember = "Value"; 
     cb.DataSource = data; 
    } 

    public void DistributeCB2(ComboBox cb) 
    { 
     BooksDBDataContext db = new BooksDBDataContext(); 

     //Publishers table 
     var data = db.Publishers.Select(publisher => new 
     { 
      Id = publisher.PublishingId, //field 1 
      Value = publisher.PublishingName //field 2 
     }); 
     cb.ValueMember = "Id"; 
     cb.DisplayMember = "Value"; 
     cb.DataSource = data; 
    } 

回答

1

好吧,如果你不介意傳遞實體作爲一個通用型的,而不是一個字符串參數,你可以嘗試:

對LINQ到實體:

public void Distribute<TEntity>(ComboBox cb, 
           DbContext db, 
           string valueField, 
           string displayField) 
         where TEntity : class 
{ 

    //Publishers table 
    var data = db.Set<TEntity>() as IEnumerable; 

    cb.ValueMember = valueField; 
    cb.DisplayMember = displayField; 
    cb.DataSource = data; 
} 

對LINQ到SQL:

public void Distribute<TEntity>(ComboBox cb, 
           DataContext db, 
           string valueField, 
           string displayField) 
         where TEntity : class 
{ 

    //Publishers table 
    var data = db.GetTable<TEntity>() as IEnumerable; 

    cb.ValueMember = valueField; 
    cb.DisplayMember = displayField; 
    cb.DataSource = data; 
} 
+0

看起來不錯,我會嘗試, – user1652656

+0

這裏的問題是,你會從獲取的所有列數據庫,而不僅僅是你需要的兩個。 – Servy

+0

它的好處是我的目的,因爲我只想用它只包含2個字段的表,但我從編輯器中得到錯誤 - 我不確定它是什麼意思:( – user1652656

0

我嘗試一些東西,它的工作原理,但我敢肯定它的代碼:

public void Distribute<TEntity>(ComboBox cb, BooksDBDataContext db, string valueField, string displayField) 
        where TEntity : class 
    { 


     var data = db.GetTable<TEntity>(); 


     cb.ValueMember = valueField; 
     cb.DisplayMember = displayField; 
     cb.DataSource = data; 
    }