none
User.Documents.FirstOrDefault(predicate) style query? not generating SQL I expect? RRS feed

  • Question

  • I want to find a specific Document for a particular User and am doing this ...

    User.Documents.FirstOrDefault<Document>(x => x.Name == this.Name);

    The SQL ends up looking like this ...

    SELECT [t0].[Id], [t0].[UserId], [t0].[Date], [t0].[Name], [t0].[Note], [t0].[Filename], [t0].[Type], [t0].[Size]
    FROM [dbo].[Document] AS [t0]
    WHERE [t0].[UserId] = @p0

    I would expect the WHERE clause to look something like ...

    WHERE [t0].[UserId] = @p0 AND [t0].Name = @p1

    Or am I misunderstanding how relations/queries work in LINQ?
    Sunday, August 31, 2008 6:19 PM

Answers

  • I am going to assume that User is a table and that .Documents is an entity set created using the database relations.

     

    Look at your query:

     

    User.Documents.FirstOrDefault<Document>(x => x.Name == this.Name);

     

    User.Documents is the datasource - it returns the list of documents using EntitySet. When you call any entityset property, LINQ to SQL populates it with objects - hence the query you are seeing.

     

    If you want to get just the document desired, construct the query from the table:

     

    var doc = db.Documents.FirstOrDefault( x => x.UserID == User.UserID && x.Name == this.Name);

     

    Tuesday, September 2, 2008 1:35 PM
    Answerer

All replies

  • I am going to assume that User is a table and that .Documents is an entity set created using the database relations.

     

    Look at your query:

     

    User.Documents.FirstOrDefault<Document>(x => x.Name == this.Name);

     

    User.Documents is the datasource - it returns the list of documents using EntitySet. When you call any entityset property, LINQ to SQL populates it with objects - hence the query you are seeing.

     

    If you want to get just the document desired, construct the query from the table:

     

    var doc = db.Documents.FirstOrDefault( x => x.UserID == User.UserID && x.Name == this.Name);

     

    Tuesday, September 2, 2008 1:35 PM
    Answerer
  • Ok, thanks, that is what I am doing.

    I am coming from a Rails and ActiveRecord world, and they have some magic where if you use the User.Documents.Find(...) syntax, it automatically limits the query to Documents for that User.

    But this is fine also, just checking.
    Tuesday, September 2, 2008 4:01 PM