I use latest Entity Framework Core on .NET 8:
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.8" />
I want to get results from an arbitrary query (in addition to the normal typed flow, I want to have ability to run an arbitrary SQL query too), I simplified my code to the below console application:
using Microsoft.EntityFrameworkCore;
using System.Runtime.CompilerServices;
var c = new TestContext();
c.Database.EnsureCreated(); // passed
var result = c.Database.SqlQuery<dynamic>(
FormattableStringFactory.Create(
"SELECT * FROM History" // history table exists, but I also tried just SELECT 1 as 'Value' with same result
))
.DefaultIfEmpty() // fails with and without this step
.ToList();
// the above code fails with `Sequence contains no elements` error
Console.ReadKey();
class TestContext: DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.EnableSensitiveDataLogging(sensitiveDataLoggingEnabled: true);
optionsBuilder.UseSqlServer("MyConnectionString");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
Not sure what’s failed exactly and for what reason.
UPDATE:
It looks like the problem is related to generic type, the below code works:
var result = c.Database.SqlQuery<Dto>(
FormattableStringFactory.Create(
"SELECT 1 as 'Value'")
)
.ToList();
where Dto
is a class with single int Value
property. Is there a way to use dynamic (or similar) option here? I want to provide an arbitrary query and do not specify particular type for mapping (at least on the db level)
2