问题描述:

In my example, I have Libraries and Books.. I need to return libraries that have a certain book. I can do this fine using standard LINQ Where(.Any()), but having difficulty using Dynamic Linq.

Below is example code. My error occurs on object l4.

protected void Page_Load(object sender, EventArgs e)

{

List<Library> libraries = new List<Library>();

libraries.Add( new Library() { Name = "New York" }); // NO BOOKS FOR NY

List<Book> books = new List<Book>();

books.Add(new Book() { Title = "Colors" });

books.Add(new Book() { Title = "Gardening for Noobs" });

libraries.Add(new Library() {Name = "Boston", Books = books });

// GET NEW YORK LIBRARY

List<Library> l1 = libraries.Where(x => x.Name == "New York").ToList(); // STANDARD

List<Library> l2 = libraries.AsQueryable().Where("Name = \"New York\"").ToList(); // DLINQ

// GET LIBRARIES WITH BOOK = COLORS

List<Library> l3 = libraries.Where(x => x.Books != null && x.Books.Any(a => a.Title == "Colors")).ToList(); // STANDARD

List<Library> l4 = libraries.AsQueryable().Where("Books.any(Title = \"Colors\"").ToList(); // ERROR: No property or field 'Title' exists in type 'Library'

}

public class Library

{

private string _name;

private List<Book> _books;

public string Name

{

get { return _name; }

set { _name = value; }

}

public List<Book> Books

{

get { return _books; }

set { _books = value; }

}

}

public class Book

{

private string _title;

public string Title

{

get { return _title; }

set { _title = value; }

}

}

网友答案:

You missed one bracket and null cheking. Now it works fine

   List<Library> l4 = libraries.AsQueryable().Where("Books != null && Books.any(Title = \"Colors\")").ToList();

Update: I think that problem not in this part your code: https://dotnetfiddle.net/F2uTie

网友答案:

From memory you need to Select Books before you can use it. This only applies to navigation properties like Books...

List<Library> l4 = libraries.AsQueryable()
    .SelectMany("Books")
    .Where("Title = \"Colors\"")
    .Select("Library")
    .ToList();

You are going to need to add Library to Book

相关阅读:
Top