Music. Coding. Gaming. Life.

LINQ to Entities and constructors with parameters

Posted Saturday, December 25th, 2010 9:42:00 pm
Merry Christmas! You can tell you love something if you do it while on vacation and holidays, so let's jump right into it.

I recently converted the data access layer of Six Minutes To Release to LINQ to Entities. Aside from a bit of syntactical change, the conversion was painless. That is, until I got into the runtime:

Only parameterless constructors and initializers are supported in LINQ to Entities.

Fair enough. What I like to do is to create a class that I can quickly dump the results of a LINQ to SQL query into. Typically I'll use this for ListViews. For example:

ListView1.DataSource = (From t In db.table Select New DataClass(t, t.otherTable.Value, t.otherTable.Value2))

The problem is not that LINQ can't do this, it's specifically LINQ to Entities. So what you need to do instead is a 2-step process. First, take the data out of LINQ to Entities. Then, deal with the data in LINQ. How do you do this? By using .ToList() to process the query in LINQ to Entities and using a second query to get it into the class.

Dim query = (From t in db.table Select New With {.Table = t, .Value = t.otherTable.Value, .Value2 = t.otherTable.Value2})
ListView1.DataSource = (From q in query Select New DataClass(q.Table, q.Value, q.Value2))

Ideally, I'd like to get all this stuff out of ASP.Net and use jQuery templates instead, but that would be more legacy code converting than I have time for these days. So for now, this will be the solution I use.

Comments

Loading...
roncli.com Media Player