2014-01-16 30 views
0

我有兩個數據庫視圖Customer和CustomerOrder。我只能使用視圖而不是數據庫表。我並不需要表格,因爲我只讀取數據。每個CustomerOrder都有一個相應的客戶。使用不同列名連接兩個表

這裏是我的代碼:

namespace store.Models 
    { 
     public class CustomerOrderModel 
     { 
      [Key] 
      public String orderNumber { get; set; } 
      public String billingCustomerID { get; set; } 
      public String poNumber { get; set; } 
     } 

     public class CustomerModel 
     { 
      [Key] 
      public String customerID { get; set; } 
      public String name { get; set; } 
      public String address { get; set; } 
     } 

     public class StoreContext : DbContext 
     { 
      public DbSet<CustomerOrderModel> CustomerOrders { get; set; } 
      public DbSet<CustomerModel> Customers { get; set; } 
     } 
    } 

如何連接CustomerOrder和客戶(CustomerOrder.billingCustomerID = Customer.customerID)?

我已經看到很多關於這方面的問題,但其中大多數都連接了外鍵,並且兩個表的列名都相同。我沒有選擇更改任何列名稱的選項。

+0

你看着ForeignKeyAttribute? http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.schema.foreignkeyattribute(v=vs.110).aspx –

回答

0

我將爲此創建一個視圖模型,該視圖模型包含要發送到視圖的字段。那麼你的控制器上填充來自不同的表視圖模型

var data1 = //populate first table 
var data2 = //populate second table 
List<Model> table = new List<Model>(); 
foreach(var temp in data1){ 
    Model model = new Model(); 
    data2select = data2.Where(x => x.CustomerID = temp.billingCustomerID); 
    model.ID = temp.id; 
    model.address = data2select.address; 
    etc 
    table.add(model); 
} 

編輯:

如果你只是想你應該只創建一個列表,而不是模型的單柱,使其更簡單

List<string> list = new List<string>(); 

,並在foreach

list.add(temp.name); //the field that you want 
list.add(data2select.name); 
+0

如果我只想要一行(客戶訂單),該怎麼辦? – janinaj

+0

對於單行我只想定義一個字符串列表並添加到它,請參閱我的編輯 –

相關問題