1

我想创建一个通用方法,根据给定的参数从 Linq 获取数据,例如:table、field1 和 field2。

将使用一种方法代替这两种特定方法,例如:

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;
    }
4

2 回答 2

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-to-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;
}
于 2012-10-22T19:24:47.380 回答
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;
    }
于 2012-10-22T20:33:56.340 回答