简体   繁体   English

查询<T>等效于 EF Core 3.1

[英]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:我正在从 ASP.NET Framwork 4.7 迁移到 Asp .NET Core 3.1,但我真的陷入了以下问题:

I have a SQL query:我有一个 SQL 查询:

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?问题是如何在 EF Core 中得到结果? If the EF Core is light weight why even move from Framwork to a downgraded EF Core at all?如果 EF Core 是轻量级的,为什么还要从 Framwork 迁移到降级的 EF Core?

You can use the new EF Core 3 method FromSqlRaw() for this. FromSqlRaw()您可以使用新的 EF Core 3 方法FromSqlRaw()
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}";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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