I would like to create general method that gets data from Linq based on given parameters such as: table , field1 and field2.
one method that will be used instead of these 2 specific ones for example:
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;
}
Well if you don't mind passing the entity as a generic type instead of a string parameter you could try:
For 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;
}
For 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;
}
i tried few things and it works but i'm sure about it's code:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.