'EF Core, FromSqlRaw gives different result than query
I Use EF core 5, in dotnet 5, and i have this strange behavior of my FromSQLRaw call. When i call a Table value function.
The first time i call it everything is fine, and it uses my date paramter correct, but when i call it to update it, it seems to generate the correct query, but the result is the same as the intial call, even though i call it with a different date.
When i run
query.ToQueryString()
It returns the query i would expect, and when running that in some other software i also get the result i would expect. So my SQL string is fine.
public async Task<List<OverUnderAfdækningModel>> HentOverUnder(DateTime date)
{
var dateParam = new SqlParameter("@Dato", date);
var query = mOHandelsDbContext.OverUnderAfdæknings.FromSqlRaw("SELECT * From [MO_Handelsdata].[OverUnder].OverUnderAfdækning(@Dato)", parameters: new[] { dateParam });
var result = await query.ToListAsync();
return result ;
}
in my startup file i have
services.AddDbContext<MOHandelsDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MO_Handelsdata")));
And my service constructor looks like
public OverUnderAfdækningService(MOHandelsDbContext _mOHandelsDbContext, MORammerDbContext _mORammerDbContext)
{
mOHandelsDbContext = _mOHandelsDbContext;
mORammerDbContext = _mORammerDbContext;
}
I call the service from Blazor like below, where UpdateData is bound to a button, and SelectedDate is a DateTime bound to a datepicker
protected override async Task OnInitializedAsync()
{
await getData();
}
async Task UpdateData()
{
OverUnderAfdækninger.Clear();
getData();
}
async Task getData()
{
OverUnderAfdækninger = await OverUnderAfdækningService.HentOverUnder(SelectedDate);
}
My dbcontext looks like
public class MOHandelsDbContext : DbContext
{
public virtual DbSet<OverUnderAfdækningModel> OverUnderAfdæknings { get; set; }
public MOHandelsDbContext(DbContextOptions<MOHandelsDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<OverUnderAfdækningModel>(builder =>
{
builder.ToTable("OverUnderAfdækningModel");
});
}
}
Solution 1:[1]
It was an issue with caching.
Adding AsNoTracking() behind the query fixed it for me
var query = mOHandelsDbContext
.OverUnderAfdæknings
.FromSqlInterpolated($"SELECT * From [MO_Handelsdata].[OverUnder].OverUnderAfdækning({date})")
.AsNoTracking();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nick |
