如何在c#win表单和net5中运行sql查询,我想运行类似这样的sql查询:
SELECT CAST(FinanceDate AS DATE) AS DATE, SUM(FinancePayment) AS Payment, FinanceType FROM Finances GROUP BY CAST(FinanceDate AS DATE), FinanceType
但我有一个问题,在这种情况下和net5中,我有两个方法FromSqlInterpolated()
,FromSqlRow()
。当我使用这些方法时,我有Exception
:The required column 'ID' was not present in the results of a 'FromSql' operation
。
代码:
var finance = await dbContext.Finances.FromSqlInterpolated($"SELECT CAST(FinanceDate AS DATE) AS DATE, SUM(FinancePayment) AS Payment, FinanceType FROM Finances GROUP BY CAST(FinanceDate AS DATE), FinanceType").ToListAsync();
我能做什么
使用DbCommand执行查询:
mydbcommand.ExecuteReader( "SELECT CAST(FinanceDate AS DATE) AS DATE, SUM(FinancePayment) AS Payment, FinanceType FROM Finances GROUP BY CAST(FinanceDate AS DATE), FinanceType" );
参见https://learn.microsoft.com/en-us/dotnet/api/system.data.common.dbcommand.executereader
使用带有ID的属性[NotMapped]。
NotMappedattribution可以应用于实体类的属性我们不想在数据库
有关更多详细信息,请参阅此链接:在';从Sql';操作
不要忘记使用System.ComponentModel.DataAnnotations.Schema