如何在Entity Framework Core中执行Raw SQL

时间:2018-11-09 13:17:39

标签: asp.net-core entity-framework-core

如何在实体框架核心中没有主键的情况下使用原始SQL事务?

例如,我有以下情况:

string sql = "SELECT MaterialNumber, COUNT(DISTINCT OrderNumber) CountedOrders FROM Materials GROUP BY MaterialNumber;";
var c = db.Materials.FromSql(sql).AsNoTracking().ToArray();

材料类如下:

public class Material
{
    [Display(Name = "ID")]
    public int MaterialId { get; set; }

    [Display(Name = "Materialnummer")]
    public int? MaterialNumber { get; set; }

    [Display(Name = "Auftragsnummer")]
    public int? OrderNumber { get; set; }

    [Display(Name = "Eingelagert")]
    public bool? IsStored { get; set; }

    [Display(Name = "Einlagerdatum")]
    public DateTime StoredAt { get; set; }

    [Display(Name = "Auslagerdatum")]
    public DateTime OutsourcedAt { get; set; }

    [Display(Name = "Liefertermin")]
    public DateTime DeliveryDate { get; set; }

    [Display(Name = "Priorisiertes Material")]
    public bool PriorityMaterial { get; set; }
}

发生的错误如下:

  

InvalidOperationException:'FromSql'操作的结果中不存在必需的列'MaterialId'。

那我该如何执行这样的查询?我无法直接在数据库上下文中执行原始SQL查询。所以需要在全班就做吗?

感谢帮助

0 个答案:

没有答案