0

I have the following two tables

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

    [Required]
    [StringLength(255)]
    public string BookTitle { get; set; }

    [Required]
    [StringLength(255)]
    public string Author { get; set; }

    [Required]
    [StringLength(400)]
    public string Description { get; set; }
}

and,

public class Rating
{
    public int Id { get; set; }

    [Required]
    public int Rate { get; set; }

    public Book Books { get; set; }

    [Required]
    public int BookId { get; set; }
}

one Book can have many Ratings. I need to write a Query so that i can view the BookTitle, Author, Description and the Average Rating for each book. I know I can use a View Model but I dont know how to structure the LINQ Query

and help would be appreciated

2 Answers 2

1

One approach is to setup a navigation property on Book:

public class Book
{
    public ICollection<Rating> Ratings { get; set; }
}

Then, using Linq, you could use the reference property:

_context.Books.Select( c => new
{
    c.BookTitle,
    c.Author,
    c.Description,
    c.Ratings.Select( e => e.Rate ).Sum() / c.Ratings.Count()
});

If using a DbContext from Entity Framework, this will translate into an SQL query.

Sign up to request clarification or add additional context in comments.

Comments

1

Lets introduce a viewModel class first:

public class BookViewModel
{
    public string BookTitle { get; set; }
    public string Author { get; set; }
    public string Description { get; set; }
    public double AvgRating { get; set; }
}

We can execute the following LINQ then.

var bookViewModels = context.Books.GroupJoin(context.Ratings, x => x.Id, y => y.BookId, 
    (book, rates) => new BookViewModel
{
    Author = book.Author,
    BookTitle = book.BookTitle,
    Description = book.Description,
    AvgRating = rates.Average(r => r.Rate)
});

It may be easier for you to have Ratings navigation property in Book class.

1 Comment

Thanks very much! worked well. output is as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.