?
Solved

Is it possible to use derived tables in LINQ 2 SQL?

Posted on 2010-04-05
4
Medium Priority
?
840 Views
Last Modified: 2013-11-11
Is it possible to get something like the following in LINQ 2 SQL?

SELECT e.A, d.B
FROM
(
      SELECT * FROM Event
      WHERE ID BETWEEN 1 AND 21
) e
LEFT OUTER JOIN EventDetail d ON e.ID = d.EventID
0
Comment
Question by:Mike_Mozhaev
  • 2
4 Comments
 
LVL 12

Expert Comment

by:Chris M
ID: 29778039
Yes. You can create a view as follows:

CREATE VIEW MY_VIEW AS
SELECT e.A, d.B
FROM
(
      SELECT * FROM Event
      WHERE ID BETWEEN 1 AND 21
) e
LEFT OUTER JOIN EventDetail d ON e.ID = d.EventID

Then go to linq and simply run SELECT * FROM MY_VIEW.

Cool stuff.
0
 
LVL 3

Author Comment

by:Mike_Mozhaev
ID: 29778224
Thanks, that will work.
But I'm looking for way to express it in LINQ without any SQL since this way I have strong typing.
0
 
LVL 64

Accepted Solution

by:
Fernando Soto earned 1500 total points
ID: 29795858
Hi Mike;

Try it like this.

DataClasses1DataContext db = new DataClasses1DataContext();

var results = from ev in db.Event
              where ev.ID >= 1 & ev.ID <= 21
              join ed in db.EventDetail on ev.ID equals ed.EventID into events
              from event in events.DefaultIfEmpty()
              select new
              {
                  ev,
                  event
              };

Fernando
0
 
LVL 3

Author Closing Comment

by:Mike_Mozhaev
ID: 31710882
It works, though without derived table. But I haven't found any other way so I'll use this approach.
Thanks
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
SQL Database Recovery Software repairs the MDF & NDF Files, corrupted due to hardware related issues or software related errors. Provides preview of recovered database objects and allows saving in either MSSQL, CSV, HTML or XLS format. Ensures recov…
Stellar Phoenix SQL Database Repair software easily fixes the suspect mode issue of SQL Server database. It is a simple process to bring the database from suspect mode to normal mode. Check out the video and fix the SQL database suspect mode problem.
Suggested Courses

593 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question