2012-05-17 32 views
0

我試圖找出解決這個問題的最佳方法。我在兩個不同的數據庫中有一個客戶表(不是我所知道的理想,但它不能被修改,我必須使用我所得到的)。記錄保持同步並共享幾個字段(例如CustomerId,CustomerName等)。但他們也都有自己獨特的領域......因此,例如:我可以在Entity Framework中合併來自多個數據庫的對象嗎?

數據庫1客戶

  • 客戶編號
  • 客戶名稱
  • 字段1
  • 字段2

Database2客戶

  • 客戶編號
  • 客戶名稱
  • DifferentField1
  • DifferntField2

每個數據庫都有自己的DbContext,我可以獨立於各拉Customer對象。但我真正想要的是一個統一的Customer對象,它包含兩個dbs中的所有字段的聯合。

什麼是最好的方式來完成這個,以便我可以公開一個統一的對象?

編輯:我使用DbSet和在我的上下文對象,指定爲每個實體的映射,如下:

public DbSet<Customer> Customers { get; set; } 

,然後我的映射類具有典型的映射信息:

this.ToTable("Customer"); 
this.HasKey(t => t.CustomerId); 
this.Property(t => t.CustomerName); 

等等,所以我正在尋找一種方法來擴展這種邏輯與多個表/數據庫,並能夠執行不僅查詢,但所有必要的CRUD操作

th anks

回答

3

所有你需要做的是聲明一個類,這將代表一個統一的對象:

public class UnifiedCustomer 
{ 
    public int CustomerId {get; set;} 
    public string Name {get; set;} 
    public int Field1 {get; set;} 
    public int Field2 {get; set;} 
    public int DifferentField1 {get; set;} 
    public int DifferentField2 {get; set;} 
} 

這種類型將被用於表示來自兩個數據庫的數據:

var customers1 = dataContext1.Customers.Select(c => new UnifiedCustomer 
{ 
    CustomerId = c.CustomerId, 
    Name = c.CustomerName, 
    Field1 = c.Field1, 
    Field2 = c.Field2 
}); 
var cusomers2 = dataContext2.Customers.Select(c => new UnifiedCustomer 
{ 
    CustomerId = c.CustomerId, 
    Name = c.CustomerName, 
    DifferentField1 = c.DifferentField1, 
    DifferentField2 = c.DifferentField2 
}); 

具有兩個集合同一類型的,你可以進行聯合:

var all = customers1.Union(customers2); 
+1

我的編輯你快TYPER你... =) – EtherDragon

+0

這是可行的,但它比更復雜那看看我上面的編輯 – snappymcsnap

1

什麼是最好的方法來實現這個目的,以便我可以公開一個統一的對象?

您可能需要從每個上下文中獲取適當的結果,然後使用LINQ to Objects對內存中的結果集執行「聯合」。

+0

這是可行的,但它的複雜多了,見上面 – snappymcsnap

0

如果兩個數據庫映射到同一類,你可以簡單的做:

 using (var cx1 = new customerEntities(firstDbConnectionString)) 
     { 
      using (var cx2 = new customerEntities(secondDbConnectionString)) 
      { 
       return cx1.tCustomer.ToList().AddRange(cx2.tCustomer.ToList()); 
      } 
     } 
相關問題