我正在从ASP.NET Framwork 4.7迁移到Asp .NET Core 3.1,并且确实陷入了以下困境:
我有一个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" ;
我的自定义班级:
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; }
}
为了检索数据,我使用:
var result = Context.Database.SqlQuery<Fordonlista>(Query).ToList();
问题是如何在EF Core中获得结果?如果EF核心轻巧,为什么还要从Framwork迁移到降级的EF核心呢?
答案 0 :(得分:0)
您可以为此使用新的 EF Core 3 方法 FromSqlRaw()
。
在你的例子中,那将是
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);
但更好的是传递如下参数:
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}";