Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a holder of a property

In the following example in Entity Framework, how to find the author of a specified book using linq:

public class Author
{
    public int Id { get; set; }
    public string AuthorName { get; set; }
    public ICollection<Book> Books { get; set; }
}

public class Book
{
    public int Id { get; set; }
    public int Title { get; set; }
}

Thanks.

like image 233
Amir Parsi Avatar asked Dec 04 '25 15:12

Amir Parsi


1 Answers

Assuming you have a collection of authors, you would simply do

var author = authors.SingleOrDefault(x=> x.Books.Any(y=> y.Title.Equals(bookTitle, StringComparison.OrdinalIgnoreCase))

This assumes that books have only one author.

like image 197
Matt Avatar answered Dec 10 '25 04:12

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!