首页 > 解决方案 > DbContext.Set().SqlQuery 和 DbContext.Database.SqlQuery返回不同的结果

问题描述

SQL查询:

SELECT 0 AS Id,
       u.UserID AS UserId,
       u.first_name AS FirstName,
       u.last_name AS LastName,
       uf.uf_facility_id AS FacilityId
FROM ...

实体没有额外的映射,只是在 DbContext 中定义了属性 - public DbSet<UserFacility> UserFacilities { get; set; }

public class UserFacility
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int FacilityId { get; set; }
}

DbContext.Set().SqlQuery

返回每个项目的重复位置列表,UserFacilityUserId等于UserId第一行的值,例如:

Id  UserId  FirstName   LastName    FacilityId
0   33057   ggtest  2   3938
0   33057   QaAuOne TestOne 3938
0   33057   QaAuOne TestOne 3928

DbContext.Database.SqlQuery

返回预期结果(与在 SSMS 中运行此查询时得到的结果相同)。

Id  UserId  FirstName   LastName    FacilityId
0   33057   ggtest  2   3938
0   33098   QaAuOne TestOne 3938
0   33098   QaAuOne TestOne 3928

有人可以解释到底发生了什么以及我如何DbContext.Set<T>().SqlQuery才能返回正确的数据吗?我正在使用 EntityFramework 6.2.0。

提前致谢。

标签: c#entity-frameworkdbcontext

解决方案


推荐阅读