实体框架中的动态表名称

时间:2016-09-06 09:48:40

标签: c# entity-framework linq c#-4.0

我正在使用Entity Framwork和数据库优先方法。我想根据条件动态更改表名或视图名。

在这里,我使用V_OVT_VLD_340B_DNA_CLDV_OVT_B_tableV_OVT_c_table来获取记录。

根据源代码,我需要调用不同的表名并获取记录。除表名外,整个代码段都是相同的。

请参阅以下代码

private dOVT_OutlierViewEntities db = new dOVT_OutlierViewEntities();

if(source == "a")
{
    var result = this.db.V_OVT_VLD_340B_DNA_CLD.Where(x => x.DNA_PGM_PRTN_ID == partitionId && x.CLIENT_ID == clientId).ToList().Select(y => new ValidationModel
                {
                    claim_validation_test_id = new List<byte?> { y.CLAIM_VLD_TEST_ID },
                    claim_id = y.CLAIM_ID,
                    Provider_ID = y.Provider_ID,

                }).Take(id).ToList();
}

if(source == "b")
{
    var result = this.db.v_OVT_B_table.Where(x => x.DNA_PGM_PRTN_ID == partitionId && x.CLIENT_ID == clientId).ToList().Select(y => new ValidationModel
                    {
                        claim_validation_test_id = new List<byte?> { y.CLAIM_VLD_TEST_ID },
                        claim_id = y.CLAIM_ID,
                        Provider_ID = y.Provider_ID,

                    }).Take(id).ToList();
}

if(source == "c")
{
    var result = this.db.v_OVT_C_table.Where(x => x.DNA_PGM_PRTN_ID == partitionId && x.CLIENT_ID == clientId).ToList().Select(y => new ValidationModel
                    {
                        claim_validation_test_id = new List<byte?> { y.CLAIM_VLD_TEST_ID },
                        claim_id = y.CLAIM_ID,
                        Provider_ID = y.Provider_ID,

                    }).Take(id).ToList();

}

我想通过根据条件动态地将表名附加到db上下文来修改上述实现。

string tableName = string.empty

if(source == "a") 
    tableName = "aTable";

if(source == "b")  
    tableName="bTable";

this.db.tableName.where().....

这可能吗?

2 个答案:

答案 0 :(得分:1)

您可以使用切换条件来设置表类型并将其与上下文一起使用

switch (tableName)
        {
            case "a":
                tableType = typeof(V_OVT_VLD_340B_DNA_CLD);
                break;
            case "b":
                tableType = typeof(v_OVT_B_table);
                break;
            default:
                tableType = typeof(v_OVT_C_table);
                break;
        }

var query = context.Set(tableType);
var result = query.Find(); //filter with this query condition

答案 1 :(得分:0)

你可以这样做......

THREAD_1_START
THREAD_2_START
LOCKED_BY_1
Counter.getA()_BY_2
GET_A_BY_THREAD_2:NONE
THREAD_2_END
Counter.setA()
Counter.setA()_end
Counter.getA()_BY_1
GET_A_BY_THREAD:THREAD_1
THREAD_1_END