简体   繁体   中英

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

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. If I use DbSet, it gives me the correct record count, but the first row is duplicated over and over again.

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. We just upgraded from 2.2 where I was able to use

            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

I'd be using FromSqlInterpolated rather than FromSqlRaw, as you are using an interpolated string.

Regarding why your old code doesn't work, post up the rest of the statement as you're only showing the projection.

Efcore 3 changed the way queries are executed meaning there are some parts of complex queries you may need to do manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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