通用Linq数据方法

时间:2012-10-22 19:08:20

标签: c# linq dynamic reflection

我想基于给定的参数创建从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;
    }

2 个答案:

答案 0 :(得分:1)

如果您不介意将实体作为泛型类型而不是字符串参数传递,您可以尝试:

对于Linq-to-Entities:

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

答案 1 :(得分: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;
    }