2

I'm working on a data-driven solution using Entity Framework Core. I dynamically create SQL Server tables using ExecuteRawSQL() and build the query string based on the contents of a file I am reading in. I would like to query those tables but I do not have DbSets for them because they were created dynamically. I tried using: ExecuteRawSQL("SELECT * FROM ...") but this only returns the number of rows affected.

Ideally, I would like to get each one of the rows back from this query in the form of Dictionaries (key = column name, value = column value). Any ideas? Thanks!

2
  • 1
    Sounds like you should just use ADO.NET Commented Jun 6, 2021 at 5:21
  • @ErikEJ I went down that path and it worked like a charm! Thank you! Commented Jun 6, 2021 at 7:05

1 Answer 1

0

In EF Core you can use the DbContext Set<T>() method and then FromRawSql() to retrieve data and translate the results into a domain class that is not registered as a DbSet<T>.

In this example, I created a Cat object to represent a row in the Cats table:

public class Cat
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Breed { get; set; }
}

Now EF Core knows how to project the results:

var context = new SampleDbContext();

var cats = context
    .Set<Cat>()
    .FromSqlRaw("SELECT * FROM Cats")
    .ToList();

However, you'll have to tell EF Core to map that object to the database table on your DbContext class:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Cat>().ToTable("Cats");
}

It's also important that the object you're projecting the results to has the exact same properties as the table you're pulling the data from, otherwise you'll get an exception.

I'm not sure how you would format the results as a dictionary, but it's possible to use Select() after FromRawSql().

var links = context.Set<Cat>()
    .FromSqlRaw("SELECT * FROM Cats")
    .Select(c =>
        new
        {
            Key = nameof(c.Id),
            Value = c.Id
        });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.