Enable flexible FromSql mapping

Open
#21,627 5 comments 24 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
30/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
csharp, sql
Domain
database

Research direction

Start by reviewing the linked issues 17063 and 13358, then inspect the existing ToSqlQuery, FromSql, and FromSqlRaw entry points. Define the supported mapping and parameter configuration behavior, including named, default, and JSON-column queries, before identifying the required tests and implementation scope.

Written by the indexing model from the issue text.

Description

area-model-building area-query area-relational-mapping

This builds upon https://github.com/dotnet/efcore/issues/17063, https://github.com/dotnet/efcore/issues/13358 to enable different mappings for different SQL queries and to allow parameter configuration. This would also support JSON columns.

It would be configured like so:

modelBuilder
  .Entity<Blog>()
  .ToSqlQuery("GetDeletedBlogs", "select id as BlogId, name as BlogName from Blogs where Deleted={0}",
    q =>
    {
        q.Propety(b => b.Id).ToColumn("BlogId"));
        q.Propety(b => b.Name).ToColumn("BlogName"));
        q.Parameter("0").HasType("bit"));
    });

This also allows setting the default (unnamed) SQL query:

modelBuilder
  .Entity<Blog>()
  .ToSqlQuery("select id as BlogId, name as BlogName from Blogs where Deleted={0}",
    q => {});

A default mapping that would be used for FromSql queries and as a base configuration for mapped queries is configured like so:

modelBuilder
  .Entity<Blog>()
  .ToSqlQuery(q =>
    {
        q.Propety(b => b.Id).ToColumn("BlogId"));
        q.Propety(b => b.Name).ToColumn("BlogName"));
    });

And used like so:

var deletedBlogs = context.Set<Blog>().FromNamedSql("GetDeletedBlogs", true).ToList();

or

var deletedBlogs = context.Set<Blog>().FromNamedSqlRaw("GetDeletedBlogs",
  "select id as BlogId, name as BlogName from Blogs where Deleted={0}",
  true)
 .ToList();
Dominant language
C#
Stars
14.8k
Forks
3.4k
Avg merge
2d 5h
Merged PRs (30d)
134

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/efcore

All issues in dotnet/efcore

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.