Expose a non-generic DbSet to support operations with shared-type entity types

Open
#21,066 13 comments 7 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

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

Research direction

Start by reading the existing strongly typed FromSqlRaw methods in RelationalQueryableExtensions and the proposed non-generic IQueryable overload. Trace how the DbContext and entity metadata are used for shared-type and navigation entities. Done means establishing whether the API can support this scenario and defining the required behavior and tests.

Written by the indexing model from the issue text.

Description

area-dbcontext customer-reported

Assume a DbContext with two related DBSet<> properties like so:

public MyDbContext : DbContext
{
    public virtual DbSet<Supplier> Account { get; set; }
    public virtual DbSet<Part> Account { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        . . .
        EntityTypeBuilder<Part> partEntity
            .HasOne(d => d.Supplier)
            .WithMany(p => p.Part)
            .HasForeignKey(d => d.SupplierId);
        . . .
    }

No means exists (that I could find) to be able to the following:

public static IEnumerable DoAwesomeStuff<TEntity>(this DbSet<TEntity> dataSource, params object[] otherParameters)
	where TEntity : class
{
	string sql = "...Stuff I did to generate this internally...";
	var dbContext = (dataSource as IInfrastructure<IServiceProvider>).GetService<ICurrentDbContext>().Context;

	// Get the result
	var dbSet = dbContext.Set<TEntity>();
	var parentResults = dbSet.FromSqlRaw(sql);

	// Do other logic to hydrate navigation properties 
	string childSql = "...more stuff I did to create this for a navigation property...";
	string navigationPropertyName = (string)otherParameters[0];
	IEntityType entityType = dbContext.Model.FindEntityType(typeof(TEntity));
	var navigationProperties = entityType.GetDeclaredNavigations();
	var navigationProperty = navigationProperties.Single(p => p.Name == navigationPropertyName);
	var navigationEntityType = navigationProperty.GetTargetType();
			
	// I wrote an extension method to Get the DbSet as an IQueryable.  
        // It was the best I could do...
	var childDbSet = dbContext.GetDbSetForClrType(navigationEntityType.ClrType);

	// But even with this, all the extension methods defined in 
        // RelationalQueryableExtensions extend a strongly typed to a DbSet<>
	var childResults = childDbSet.FromSqlRaw(sql);  // <-- Not currently possible

}

private static IQueryable GetDbSetForClrType(this DbContext dbContext, Type clrType)
{
	Type DbSetType = typeof(DbSet<>);

	var propertyInfo = dbContext.GetType()
			.GetProperties(BindingFlags.Public | BindingFlags.Instance)
			.Select(p => new { PropertyInfo = p, PropertyType = p.PropertyType })
			.First(t => 
				t.PropertyType.IsGenericType && 
				t.PropertyType.GetGenericTypeDefinition() == DbSetType && 
				t.PropertyType.GetGenericArguments()[0] == clrType)
			.PropertyInfo;
	return propertyInfo.GetValue(dbContext) as IQueryable;
}

I want this because I wrote my own Uri query string parser from which I use certain information to decide which parts of a DbContext to hydrate. (Consider for example, the $expand operator that OData uses. Not only is the main entity queried, but the related entities are queried as well.)
If I want more control of the SQL generated, some solution to the above would work best.

Would it be possible to add similar methods in RelationalQueryableExtensions without the strong typing?

For example:

        [StringFormatMethod("sql")]
        public static IQueryable FromSqlRaw(
           [NotNull] this IQueryable source,
           [NotNull] [NotParameterized] string sql,
           [NotNull] params object[] parameters)
        {
            Check.NotNull(source, nameof(source));
            Check.NotEmpty(sql, nameof(sql));
            Check.NotNull(parameters, nameof(parameters));

            var queryableSource = (IQueryable)source;
            return queryableSource.Provider.CreateQuery(
                GenerateFromSqlQueryRoot(
                    queryableSource,
                    sql,
                    parameters));
        }
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.