Passiday
Passiday

Reputation: 8075

Selecting linq class from a sql object query

Learning the LINQ, trying to grasp the paradigm...

I have set up a LINQ table class for one of the core business objects. I'd like to retrieve a list of these objects from the database, using MS SQL server table objects (ie instead of defining separate LINQ classes for all the involved database tables/views). I am ok with using the LINQ criteria/join syntax, but lazy/conservative with lumps of ORM code. Maybe I am asking for something unorthodox, and it is expected in the LINQ paradigm that I build 100% replica of the database structure in LINQ classes and then make my queries using only those classes.

Upvotes: 0

Views: 413

Answers (1)

evanmcdonnal
evanmcdonnal

Reputation: 48076

What you're describing is specifically the LINQ to SQL / Entity Framework provider and this behavior isn't actually a product of LINQ. You don't need any classes at all to model what's in the database. Let say for example, I join 3 tables in my LINQ to SQL query, call them a, b, and c. You can put a select at the very end of the statement and do something like this;

RestOfLinqQuery.Select( new { name = a.name, address = b.address, height = c.height } );

And this will return an anonymous object composed of properties from the three tables. Also, you could make an object which has the various properties from tables a, b, and c and use the same style of initialization or make a constructor that takes in all of the fields you want to set and create it. The Table to Object mapping is created by Entity Framework, LINQ is not restricted by that at all.

EDIT: This answer has a good example of full queries, better than my little example; How do I convert multiple inner joins in SQL to LINQ? As you can see there the same type of initialization is used to set properties of the newly created object from more than 1 table.

Also, if you're working on an enterprise application and running into this problem a good solution is to create view in the db which do all the joins for you and then model the views in C# rather than modeling tables who's rows don't actually represent useful objects.

Upvotes: 1

Related Questions