I have the following Linq2Sql and it does more than one round for my SELECT statement. I do not know why. Code first, then explanation: -
from p in db.Questions select new Models.Question { Title = p.Title, TagList = (from t in p.QuestionTags select t.Tag.Name).ToList() }
Database now
Questions <-one to many-> QuestionTags <-many to one-> Tag
therefore, one question has one, many tags, and the link table is in the middle. This way I can reuse tags several times. (I am open to a better scheme, if any).
To do this, the following Sql code generated by Linq2Sql is executed
SELECT [t0].[QuestionId] AS [ID], etc.... <
.
exec sp_executesql N'SELECT [t1].[Name] FROM [dbo].[QuestionTags] AS [t0] INNER JOIN [dbo].[Tags] AS [t1] ON [t1].[TagId] = [t0].[TagId] WHERE [t0].[QuestionId] = @x1',N'@x1 int',@x1=1
The second sql block is specified 2x .. I think because the first sql block returns TWO results, so the second one is launched for each result from the first.
Is there a way to make this one SQL query instead of 1 + n, where n = the number of results of the first query?
Update:
I have tried both loading and lazy loading, and there is no difference.
DataLoadOptions dataLoadOptions = new DataLoadOptions(); dataLoadOptions.LoadWith<Question>(x => x.QuestionTags); dataLoadOptions.LoadWith<QuestionTag>(x => x.Tag); db.LoadOptions = dataLoadOptions;
Pure.Krome
source share