0

Is there a cleaner way to dynamically select a table from a context in Entity Framework? Maybe in a for next loop? If else else then is possible but looks messy and there are about 10 tables that we will need to handle. All the field names are the same in the tables. We are using .Net 6 already and VS 2022. So if there is a newer feature I am up for it.

await using timeFrameContext context = new();

var existsAlready = await context.FiveMin
    .AnyAsync(t => t.ProductName == symbol).ConfigureAwait(false);

var existsAlready = await context.FifteenMin
    .AnyAsync(t => t.ProductName == symbol).ConfigureAwait(false);

var existsAlready = await context.ThirtyMin
    .AnyAsync(t => t.ProductName == symbol).ConfigureAwait(false);

etc ...

1
  • 1
    DbContext.Set<TEntity>()? Commented Sep 30, 2021 at 14:44

1 Answer 1

1

Do you need somthing like this.

public async Task<bool> exist<T>(Expression<Func<T, bool>> condition) where T : class
{
    return await _contextDb.Set<T>().AnyAsync(condition);
}

then you can call in this way

var a = await existAsync((FiveMin t) => t.ProductName == symbol);
var b = await existAsync((FifteenMin t) => t.ProductName == symbol);
var c = await existAsync((ThirtyMin t) => t.ProductName == symbol);
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.