Dynamic creation of EF 6 Core query

Viewed 13

I have a client and a server, and the client asks the server to read or write a specific DbSet-Entity. The function looks like:

[HttpGet("genericlist")]
[ProducesResponseType(typeof(List<BaseEntity>), 200)]
[ProducesErrorResponseType(typeof(string))]
public ObjectResult GetGenericList([FromQuery] string typeName)
{
    if (!TryGetProp(typeName, out PropertyInfo prop, out Type? type))
        return new BadRequestObjectResult("invalid typename");

    var dbSet = prop.GetValue(_context);
            
    if (dbSet == null)
        return new BadRequestObjectResult("type not found in database");


    return Ok(dbSet);
}

That works great. It even works greater with this snippet in the OnModelCreating(ModelBuilder modelBuiler) method to include all the sub-entities in the query:

modelBuilder
    .Entity<Product>()
    .Navigation(a => a.ContainerList)
    .AutoInclude();

But I have a huge problem with this AutoInclude when updating or inserting, it always gets in conflict with entries that are referenced more than once in the EF6 graph. The only solution I came up with was to remove the AutoInclude, put a custom "Include" attribute over includable properties in the model and rewrite the GetGenericList method to build the query myself, for example:

_context.Product.Include(a => a.ContainerList);

But I would like to keep it generic, and I do not have any idea left how to do this call in a generic way. How do I get the properties, so that I can attach a .Include?

Something like that would be great:

ContextProperty(_context, type).Include(a => FindProperty(...))

Any help would be greatly appreciated. :)

0 Answers
Related