0

我有一个连接到 4 个数据库的程序。在其中三个数据库中,实体对象非常相似。现在我的问题很简单,但我不知道如何继续。

我有三个数据库让我们称它们为 1 2 和 3 在那些我有几个表 ab 和 c

我在问,因为 1a 和 2a 和 3a 几乎相同,有没有办法让我做这样的事情。?

Using(interfaceDB DB = new DB1())
{
   var getTabelA = (from a in DB.a select a);
}
Using(interface DB = new DB2())
{
   var getTabe2A = (from a in DB.a select a);
}
Using(interface DB = new DB3())
{
   var getTabe3A = (from a in DB.a select a);
}
foreach(interfaceDBTableA in getTabelA)
{
   //do something here
}
foreach(interfaceDBTableA in getTabe2A )
{
   //do something here
}
foreach(interfaceDBTableA in getTabe3A )
{
   //do something here
}

基本上我的希望是我可以将循环部分放入它自己的方法中并重用它而不需要将它定制到单个表?

4

1 回答 1

0

您可以定义一个接口,其中包含您的对象共有的成员,如下所示:

public interface ICommonStuff
{
    int CommonInt
    {
        get;
    }

    string CommonString
    {
        get;
    }
}

...然后在类中实现该接口AB并且C

public class A : ICommonStuff
{
    public int AInt { get; set; }

    public string AString { get; set; }

    public int CommonInt
    {
        get { return this.AInt; }
    }

    public string CommonString
    {
        get { return this.AString; }
    }
}

public class B : ICommonStuff
{
    public int BInt { get; set; }

    public string BString { get; set; }

    public int CommonInt
    {
        get { return this.BInt; }
    }

    public string CommonString
    {
        get { return this.BString; }
    }
}

... (same for C)

然后你应该能够像这样选择它们:

using (interfaceDB DB = new DB1())
{
    var getTable1A = (from a in DB.a select a).Cast<ICommonStuff>();
}

using (interface DB = new DB2())
{
    var getTable2A = (from a in DB.a select a).Cast<ICommonStuff>();
}

using (interface DB = new DB3())
{
    var getTable3A = (from a in DB.a select a).Cast<ICommonStuff>();
}

var everythingLikeA = getTable1A.Concat(getTable2A).Concat(getTable3A);

foreach (ICommonStuff commonStuff in everythingLikeA)
{
    // do something here with commonStuff.CommonInt and commonStuff.CommonString
}
于 2012-04-20T10:40:25.310 回答