LINQ against dynamic object

◇◆丶佛笑我妖孽 提交于 2020-01-05 13:53:48

问题


I am implementing an import tool that reads data from file and stores them to a database. We have one database in two different editions: a "full" edition and a "lightweight" edition. The lightweight edition has one table less plus four other tables which reference the missing table also don't have this foreign key column.

I have already implemented the tool to import the data into the "full" database using Linq-to-Sql and I want to re-use the logic for the import to the lightweight version of the database.

My idea was to use dynamic objects for this purposes.

So I added two different Linq-To-SQL .dbml files to my project and populated them with the respective table. I set them to use different namespaces to avoid name clashing.

I have no problems to initialize the DbContext (at least I don't get any compiler error here) of the dynamic variable:

            bool _usefirstdb; 
            dynamic _db;
            if (_usefirstdb) 
            {
                _db =  new FirstDBDataContext (string.Format(SqlScripts.SqlServerConnectionString, args[1], args[2]));
            }
            else
            {
                _db =  new SecondDBDataContext(string.Format(SqlScripts.SqlServerConnectionString,args[1], args[2]));
            }

but I got problems with running LINQ queries against this objects:

      var query = from inst in _db.Instances
                  where inst.Name.Equals(args[3])
                  select inst.Id;

This is because the type of inst cannot be determined by the compiler (and is not dynamic).

Is there any way to overcome this problem? I know that C# is statically type, but I don't see any other way to re-use my code...


回答1:


When both of your DbContext classes implement the same interface you can have the reference as that interface. In your interface you keep the DbSet's that both of your contexts have. Then when you use linq you can query only those sets and it is still type safe.

Like so:

public interface IInstances
{
    DbSet<Instance> Instances { get; }
}

public FirstDBDataContext :DbContext, IInstances
{
    //Normal implementation
}

public SecondDBDataContext :DbContext, IInstances
{
    //Normal implementation
}

bool _usefirstdb; 
IInstances _db;
if (_usefirstdb) 
{
    _db =  new FirstDBDataContext (string.Format(SqlScripts.SqlServerConnectionString, args[1], args[2]));
}
else
{
    _db =  new SecondDBDataContext(string.Format(SqlScripts.SqlServerConnectionString,args[1], args[2]));
}

var query = from inst in _db.Instances
    where inst.Name.Equals(args[3])
    select inst.Id;


来源:https://stackoverflow.com/questions/16718748/linq-against-dynamic-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!