efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Enable flexible FromSql mapping

Open AndriySvyryd opened this issue 5 years ago • 5 comments
trafficstars

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>()
  .HasQuerySql("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"));
    });

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();

AndriySvyryd avatar Jul 14 '20 21:07 AndriySvyryd

In your second example, you did mean?

var deletedBlogs = context.Set<Blog>().FromNamedSqlRaw("GetDeletedBlogs",
  "select id, name from Blogs where Deleted={0}",
  true)
 .ToList();

I suppose that Blog class have Id and Name properties, and should be filled by convection through sql fields and class property's names, correct?

ircnelson avatar Jul 16 '20 14:07 ircnelson

@ircnelson No, the example shows that column names can be customized for raw SQL queries without affecting the table to which the entity type is also mapped.

AndriySvyryd avatar Jul 16 '20 17:07 AndriySvyryd

Also add a note to the CustomQueryMappingOnOwner exception suggesting to use named queries

AndriySvyryd avatar Jul 24 '20 23:07 AndriySvyryd

Also consider API to mark the SQL as non-composable so we would run it as-is.

smitpatel avatar Jul 28 '20 20:07 smitpatel

Related: https://github.com/dotnet/efcore/issues/21827, #21660

AndriySvyryd avatar Jul 28 '20 21:07 AndriySvyryd