Smilley Smilley - 5 months ago 34
C# Question

How to use dynamic DbSet in Entity Framework?

coluld you please be so kind to tell me how do I choose DbSet depending on string variable? What I have is the following:

public class DataContext : DbContext
public DataContext() : base("myDb") { }

public DbSet<Entry> RurEntries { get; set; }
public DbSet<Entry> UsdEntries { get; set; }
public DbSet<Entry> EurEntries { get; set; }

There are 3 tables for each currency: Rur,Usd,Eur. All have same structure.
There is string variable named CurrentCurrency which is changed from UI and may be one of 3 currencies. In my previous code without Entity Framework I had code that read db with pure sql, someting like:

string sqlQuery = "Select * from " + CurrentCurrency

Now I decided to rewrite code with Entity Framework and faced that problem. Any answer will be appreciated. Thanks in advance.


You can simply switch on your CurrentCurrency string to get set that you need:

 var db = new DataContext();
        var CurrentCurrency = "RUR";
        DbSet<Entry> set = null;
        switch (CurrentCurrency) {
            case "RUR":
                set = db.RurEntries;
            case "EUR":
                set = db.EurEntries;
            case "USD":
                set = db.UsdEntries;
                throw new Exception();
        var res = set.ToList();