I’m attempting to create a ViewModel that utilises data from 2 separate entities.
I want my ViewModel to show all the data from a Game class and have the corresponding developerName value attached from the Developer model.
I’m populating a model variable with data from the game class and trying to include the developers name by calling a helper method that outputs the name of the developer when it’s provided an ID.
This will of course not work, the LINQ query will fail with a NotSupportedException stating:
LINQ to Entities does not recognize the method 'System.String GetDeveloperNameFromId(Int32)' method, and this method cannot be translated into a store expression.
This is the current attempt:
GameController.cs
var model = _db.Games
.OrderByDescending(r => r.Name)
.Select(r=> new GameViewModel
{
Id = r.Id,
Name = r.Name,
Rating = r.Rating,
ReleaseDate = r.ReleaseDate,
Type = r.Type,
DeveloperId = r.DeveloperId,
DeveloperName = GetDeveloperNameFromId(r.DeveloperId)
})
.Where(r => searchTerm == null || r.Name.StartsWith(searchTerm));
private string GetDeveloperNameFromId(int id)
{
var _model = _db.Developers.FirstOrDefault(r => r.Id.Equals(id));
string _name = _model.Name;
return _name;
}
GameViewModel.cs
public class GameViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Rating { get; set; }
public DateTime ReleaseDate { get; set; }
public string Type { get; set; }
public string DeveloperName { get; set; }
public int DeveloperId { get; set; }
}
Game.cs
public class Game
{
public int Id { get; set; }
public string Name { get; set; }
public string Rating { get; set; }
public DateTime ReleaseDate { get; set; }
public string Type { get; set; }
[Display(Name = "Developer")]
public int DeveloperId { get; set; }
}
I’m certain there’s a better method to adding the developer name, perhaps with a join LINQ query, or perhaps modifying the scope of the model variable to include multiple entities?
Even better would be to have the DeveloperName field be populated automatically in the ViewModel, is that possible?
I solved this after reading Martins comment, I added a foreign key reference to the game.cs entity which allows access the related developer data.
GameController.cs
game.cs