Dynamic Linq - 如何从子属性中选择父对象

时间:2016-10-31 15:14:02

标签: c# linq

在我的例子中,我有Libraries and Books ..我需要返回有某本书的库。我可以使用标准的LINQ Where(.Any())做到这一点,但是使用Dynamic Linq时遇到了困难。

以下是示例代码。我的错误发生在对象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; }
        }
    }

2 个答案:

答案 0 :(得分:1)

你错过了一个支架并且没有检查。现在它工作正常

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

更新: 我认为这个问题不在你的代码中: https://dotnetfiddle.net/F2uTie

答案 1 :(得分:0)

从内存中,您需要选择Books才能使用它。这仅适用于Books ...

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

您需要将Library添加到Book