3

I am trying to join two table and create a tuples list but getting error as 'Only parameterless constructors and initializers are supported in LINQ to Entities'

var list = (
    from a in db.CategoryRatings
    join c in db.OverallPerformanceByCategories
        on a.CategoryRatingId equals c.CategoryRatingId
    where c.ReviewId == review.ReviewId
    select(new Tuple<string, double, double>(a.CategoryRatingName, a.CategoryWeight, c.Score))
).ToList(); 

ViewData["ListOverallRating"] = list;

I don't want to create an anonymous type list to using tuples, can suggest other way as well.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
Rocky
  • 4,454
  • 14
  • 64
  • 119
  • 1
    I think it couldn't be translated to T-SQL, Linq to Entities couldn't recognize it. I guess using `ToList` or `AsEnumerable` solve your problem https://stackoverflow.com/a/41802414/2946329 – Salah Akbari Aug 07 '18 at 19:36
  • 1
    Fundamentally your problem is that you are asking **SQL server** to create a Tuple, it can't create *Tuples*. So that's why you should create anonymous objects and after they are returned locally to C# you can then translate/materialize them into whatever object you want (as suggested by Miguel). – Erik Philips Aug 07 '18 at 19:47
  • 1
    Also, assuming you're using [tag:asp.net-mvc] by your codes references to `ViewData`, I suggest you look into using ViewModels instead. – Erik Philips Aug 07 '18 at 19:48

1 Answers1

10

Use the anonymous type to fetch from the database and convert to a Tuple in memory.

var list = (
    from a in db.CategoryRatings
    join c in db.OverallPerformanceByCategories
        on a.CategoryRatingId equals c.CategoryRatingId
    where c.ReviewId == review.ReviewId
    select(new {a.CategoryRatingName, a.CategoryWeight, c.Score})
)
.AsEnumerable()
.Select(t =>
    new Tuple<string, double, double>(t.CategoryRatingName, t.CategoryWeight, t.Score))
.ToList(); 

ViewData["ListOverallRating"] = list;

Hope this help!

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
Miguel
  • 3,786
  • 2
  • 19
  • 32