Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic property access for generated LINQ Classes

How can I access dynamically properties from a generated LINQ class ?

Cause I would like to be able to customize the displayed table columns where Partner is the LINQ Class generated from a SQL Server Database Table.

<table class="grid">
  <thead>
   <tr>
     <% foreach (Column c in (IEnumerable)ViewData["columns"]) { %>
     <th><%= c.Title %></th>    
     <% } %>                               
   </tr>
 </thead>
 <tbody>
 <% foreach (Partner p in (IEnumerable)ViewData.Model) { %>
   <tr>
     <% foreach (Column c in (IEnumerable)ViewData["columns"]) { %>
?????   <th> <%= p.GetProperty(c.Name) %>  </th>  ?????
     <% } %>         
   </tr>       
 <% } %>
  </tbody>
</table>

Any idea how the code of the p.GetProperty(c.Name) method could look like ?

Forgive me if the Question is very simple but as I'm new to C# and LINQ I really couldn't figure it out.

like image 669
Oliver Avatar asked Nov 25 '25 10:11

Oliver


1 Answers

Reflection should provide what you want - in particular,

typeof(Partner).GetProperty(c.Name).GetValue(p, null)

However, you might want to do this before the loop:

var columns = (IEnumerable<string>)ViewData["columns"];
var cols = columns.Select(colName =>
      typeof(Partner).GetProperty(colName)).ToList();

This gives you a set of re-usable PropertyInfo instances that you can use per row:

 foreach (var col in cols) { %>
     <th><%= col.GetValue(p,null) %></th>
 <% }

(should that <th/> be a <td/>, by the way?)

That should be a bit more efficient than repeatedly finding each property. There are other ways of doing this too (faster again).

like image 113
Marc Gravell Avatar answered Nov 27 '25 22:11

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!