0

How to use Take() with the following code?

var context = new Entities();
BindingSource bi = new BindingSource();
var TableName = cboSelectTable.Text.ToString();    
bi.DataSource = context.GetType().GetProperty(TableName).GetValue(context, null);

Thanks.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
feather
  • 85
  • 1
  • 2
  • 13

1 Answers1

1

You'd need to cast the result of GetValue() to something appropriate. Is it always going to be a sequence of some class type? If so, as of C# 4 and .NET 4 you could use generic covariance:

var context = new Entities();
var tableName = cboSelectTable.Text.ToString();    
var rawData = context.GetType().GetProperty(TableName).GetValue(context, null);
var truncatedData = ((IQueryable<object>) rawData).Take(100);
var source = new BindingSource { DataSource = truncatedData };

You may also want to call ToList() after Take(100), to materialize the query results.

(This is assuming it will be an IQueryable<T>... if it's just just an IEnumerable<T>, cast to that instead.)

It's not clear what Entities is, but it's entirely possible that there's a way of getting the data out without using reflection - if you could give us more information, we could help more.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I am using an entity framework actually, the full code is as follows: var context = new AdminEntities(); BindingSource bi = new BindingSource(); var TableName = cboSelectTable.Text.ToString(); bi.DataSource = context.GetType().GetProperty(TableName).GetValue(context, null); dgvLoadTable.DataSource = bi; dgvLoadTable.Refresh(); – feather Oct 09 '14 at 10:55
  • 1
    @feather: No, don't post a load of code in the comments. But if you could tell us what `Entities()` inherits from, that would be helpful... – Jon Skeet Oct 09 '14 at 10:55
  • It's an entity model built using database tables – feather Oct 09 '14 at 10:56
  • 1
    @feather: That doesn't answer my question. (I'm not an Entity Framework developer myself, but if you could tell me the base class of `Entities`, that would really help me find more information...) – Jon Skeet Oct 09 '14 at 11:01
  • I have two database, I built the entity model by using the tables of those database. The line is actually var context= new AdminEntities().Here AdminEntities is an entity model. – feather Oct 09 '14 at 11:06
  • Again, you haven't answered the question. It's a pretty simple question: what's the base class? I'm trying to help you - *please* help me to help you. – Jon Skeet Oct 09 '14 at 11:07
  • Thanks a lot, maybe I couldn't make you understand my problem. But I figured out the solution with the help of your answer. It's working now . – feather Oct 09 '14 at 13:43