【问题标题】:LINQ against two different data contexts using interfaces使用接口针对两个不同的数据上下文进行 LINQ
【发布时间】:2013-05-24 09:33:39
【问题描述】:

这是我提出的问题here 的延续。

简要总结:我有两个不同的数据库,变化很小(一个表和一个表中缺少它的外键),我希望使用 Linq-To-Sql 的导入实用程序能够在不重复逻辑的情况下用数据填充两个数据库。

我的第一种方法是使用dynamic 将两个不同的数据库上下文存储在一个变量中,但这种方法不起作用,建议我为此使用接口。

现在我遇到了以下问题:

我从我的数据库上下文类中正确提取了接口:

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

...但为了能够通过两个不同的数据库上下文类来实现接口,我不得不用接口替换实际的 LINQ 类(FieldCollectionField)。

现在我在类实现中返回 Table&lt;IFieldCollection&gt;Table&lt;IField&gt; 时遇到问题。 db 上下文类的自动生成代码如下:

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

所以,为了在这里实现IDataContext,我需要将返回值更改为Table&lt;IFieldCollection&gt;。然后如何在我的属性获取器中将Table&lt;FieldCollection&gt; 转换为Table&lt;IFieldCollection&gt;而不从数据库中检索完整的表

【问题讨论】:

    标签: c# linq generics interface


    【解决方案1】:

    在我的 testapp 中,以下似乎有效。

    像这样定义你的界面:

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

    使用以下实现更新您的数据上下文:

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

    现在,例如,如果您使用 .Where(&lt;predicate&gt;).FirstOrDefault() 进行查询,则查询将正确编译,并在 SQL 中具有相应的 WHERE。

    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
    }
    

    【讨论】:

    • 感谢您的解决方案。即使没有Cast&lt;&gt;() 这里也可以工作。
    • 是的,当然。很明显,现在想起来了。我会更新答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 2015-11-04
    • 2021-01-08
    • 2013-04-16
    相关资源
    最近更新 更多