简体   繁体   中英

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;
            break;
            case "EUR":
                set = db.EurEntries;
            break;
            case "USD":
                set = db.UsdEntries;
            break;
            default:
                throw new Exception();
        }
        var res = set.ToList();

You can only use an entity class T in a DbSet<T> once per DbContext. Your code won't run. See also Entity Framework 6 Creating Two table from the same entity object .

Given your comment:

All 3 tables have unique_id field, which I receive from another software. I used unique flag on that column and it might be a problem if i put all entries to the same table

You just need a composite primary key, comprised of Currency and ExternalId, as explained in Composite Key with EF 4.1 Code First :

public class Entry
{
    [Key]
    [Column(Order = 0)]
    public string Currency { get; set; }

    [Key]
    [Column(Order = 1)]
    public string ExternalId { get; set; }
}

Then you can read the "EUR" rows like this:

var eurRows = dbContext.Entries.Where(e => e.Currency == "EUR");

You can execute raw SQL queries in Entity Framework. Like this:

var curs = context.Database.SqlQuery<Entry>("Select * from " + CurrentCurrency").ToList();

You can also make that more neat and create a stored procedure, where you send a parameter and execute a SELECT statement based on that parameter. Then using Entity framework, you call that procedure an map the results to a List<Entry> .

However, and as I stated in the comments I do personally prefer to have only one table with a CurrenyCode column. Instead of having 3 tables with the exact same structure but with different data. Then you can query like this:

var curs = var curs = context.Currencies.Where(x=> x.CurrencyCode = CurrentCurrency)
                                        .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM