Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework bind raw SQL query to model class

I got assignment to develop football table management system. I decided to do it using asp.net mvc. Only requirement is to use raw SQL queries. So that means I can't use linq or lambda. I would like to do something like this:

using (var context = new FootballTableContext())
{
     var players = context.Database.SqlQuery<PlayerViewModel>("SELECT Vardas, Pavarde FROM ZAIDEJAS").ToList();
}

but after executing this code, I Get a list of PlayerViewModel with null values.

ViewModel class:

public class PlayerViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Context class:

public class FootballTableContext : DbContext
{
    public FootballTableContext() : base("DefaultConnection") { }
}

So my question is how to bind that query to my ViewModel?

like image 279
Mazas Avatar asked Mar 10 '23 08:03

Mazas


1 Answers

Do it like this:

var players = dbContext.Database
    .SqlQuery<PlayerViewModel>("SELECT Vardas as FirstName, Pavarde as LastName FROM ZAIDEJAS")
    .ToList<PlayerViewModel>();

It is known as SQL queries for non-entity types.

like image 143
CodingYoshi Avatar answered Mar 28 '23 15:03

CodingYoshi