简体   繁体   English

Entity Framework Core 3.0 使用 DbSet vs.DbQuery 和 FromSqlRaw 时的不同结果

[英]Entity Framework Core 3.0 different results when using DbSet vs.DbQuery and FromSqlRaw

If I call the same code:如果我调用相同的代码:

return _context.dtoCostCodes <br>.FromSqlRaw($"SELECT distinct '' as ID, CostCode, BusinessUnitID from CostCodes where IsActive = 1 and BusinessUnitID = '{id}'").ToList();

First with my DBContext set as首先将我的 DBContext 设置为

public DbQuery<DTO.dtoCostCode> dtoCostCodes { get; set; }

and then with:然后用:

public DbSet<DTO.dtoCostCode> dtoCostCodes { get; set; }

The DbQuery gives me the correct results in both record count and data. DbQuery 为我提供了记录计数和数据的正确结果。 If I use DbSet, it gives me the correct record count, but the first row is duplicated over and over again.如果我使用 DbSet,它会为我提供正确的记录数,但第一行会一遍又一遍地重复。

Any idea to the cause of this behavior?知道这种行为的原因吗?

My concern is that in .net Core 3.0 DbQuery is obsolete and I'll run into different issues down the line.我担心的是,在 .net Core 3.0 DbQuery 中已过时,我会遇到不同的问题。 We just upgraded from 2.2 where I was able to use我们刚刚从我可以使用的 2.2 升级

            select new dtoCostCode
        {
            ID = c.ID,
            JDECostCode = c.JDECostCode,
            BusinessUnitID = c.BusinessUnitID
        }).Where(cc => cc.BusinessUnitID == id).GroupBy(cc => cc.JDECostCode).Select(y => y.First()).Distinct().ToListAsync();

But it is no longer supported in 3.0但在 3.0 中不再支持

I'd be using FromSqlInterpolated rather than FromSqlRaw, as you are using an interpolated string.我将使用 FromSqlInterpolated 而不是 FromSqlRaw,因为您使用的是插值字符串。

Regarding why your old code doesn't work, post up the rest of the statement as you're only showing the projection.关于为什么您的旧代码不起作用,请张贴声明的 rest,因为您只显示投影。

Efcore 3 changed the way queries are executed meaning there are some parts of complex queries you may need to do manually. Efcore 3 改变了查询的执行方式,这意味着您可能需要手动执行复杂查询的某些部分。

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

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