简体   繁体   中英

SqlQuery<T> equivalent in EF Core 3.1

I am migrating from ASP.NET Framwork 4.7 to Asp .NET Core 3.1 and I am really stuck in the following:

I have a SQL query:

string Query=" 
SELECT I.Id,I.Combokod,I.S_Omr,I.Date,M.Price,M.Name,M.Dmedel,M.Year,M.Miles 
    FROM dbo.Itemannounces AS I  
    INNER JOIN dbo.MotorDBs AS M ON I.MotorDBs_Id=M.Id  where M.MotorID=1" ;

My customized class:

public class Fordonlista
        {
        public int Id { get; set; }
        public byte Combokod { get; set; }
        public byte Affarsform { get; set; }
        public byte Model { get; set; }
        public byte Dmedel { get; set; }
        public short Year { get; set; }
        public int Miles { get; set; }
        public short S_Omr { get; set; }
        public DateTime Date { get; set; }
        public int Price { get; set; }
        public string Name { get; set; }
        public string Lan { get; set; }
        public string Kommun { get; set; }
        public byte Typ { get; set; }
        }

In order to retreive the data I use:

var result = Context.Database.SqlQuery<Fordonlista>(Query).ToList(); 

The question is how to get the result in EF Core? If the EF Core is light weight why even move from Framwork to a downgraded EF Core at all?

You can use the new EF Core 3 method FromSqlRaw() for this.
In your example that would then be

string Query=" 
    SELECT I.Id,I.Combokod,I.S_Omr,I.Date,M.Price,M.Name,M.Dmedel,M.Year,M.Miles 
    FROM dbo.Itemannounces AS I  
    INNER JOIN dbo.MotorDBs AS M ON I.MotorDBs_Id=M.Id
    where M.MotorID=1" ;
var result = Context.Fordonlista.FromSqlRaw(Query);

But even better would be to pass a parameter as following:

int motorId = 1; //or passed in from other variable
var result = Context.Fordonlista.FromSqlInterpolated(
    $"SELECT I.Id,I.Combokod,I.S_Omr,I.Date,M.Price,M.Name,M.Dmedel,M.Year,M.Miles
      FROM dbo.Itemannounces AS I  
      INNER JOIN dbo.MotorDBs AS M ON I.MotorDBs_Id=M.Id
      WHERE M.MotorID={motorId}";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM