LINQ against two different data contexts using interfaces

孤街醉人 提交于 2019-12-09 03:24:32

问题


This is the continuation of my question asked here.

Brief summary: I have two different databases with minimal changes (one table and foreign keys to it are missing in one table) and I want my import utility that uses Linq-To-Sql to be able to populate both databases with data without duplication of the logic.

My first approach was to use dynamic storing two different database contexts in a single variable, but this approach did not work and I was recommended to use interfaces for this purpose.

Now I bumped into the following problem:

I correctly extracted interfaces from my db context class:

public interface IDataContext
{
    System.Data.Linq.Table<IFieldCollection> FieldCollections { get; }
    System.Data.Linq.Table<IField> Fields { get; }
}

... but in order to be able to implement the interface by two different database context classes I had to substitute the actual LINQ classes (FieldCollection, Field) with interfaces as well.

Now I have problems with returning Table<IFieldCollection> or Table<IField> in my class implementation. The auto-generated code for the db context class is the following:

    public System.Data.Linq.Table<FieldCollection> FieldCollections
    {
        get
        {
            return this.GetTable<FieldCollection>();
        }
    }

So, in order to implement IDataContext here I need to change the returning value to Table<IFieldCollection>. How can I then cast Table<FieldCollection> to Table<IFieldCollection> in my property getter without retrieving the complete table from the database?


回答1:


In my testapp the following seems to work.

Define your interface like this:

public interface IDataContext {
    IQueryable<IFieldCollection> FieldCollections { get; }
    IQueryable<IField> Fields { get; }
}

Update your datacontexts with the following implementation:

public partial class DataContext1: IDataContext {
    IQueryable<IFieldCollection> IDataContext.FieldCollections { 
        get { return FieldCollections; }
    }
    IQueryable<IField> IDataContext.Fields { 
        get { return Fields; }
    }
}

Now, if you query for example, using a .Where(<predicate>).FirstOrDefault() then the query is compiled correctly, with a corresponding WHERE in SQL.

using (IDataContext context = MyDataContextFactory.GetInstance() /* or something else */) {
    var fieldsCount = context.Fields.Where(x => x.Id == 1).Count();
    // The predicate Id == 1 and Count() are translated to sql
}


来源:https://stackoverflow.com/questions/16731814/linq-against-two-different-data-contexts-using-interfaces

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