2016-02-12 46 views
0

我有一個現有的數據庫具有以下表:實體框架 - 代碼第一次 - 實體分割時,有沒有共享主鍵

Customer 
    customer_id (PK) 
    customer_name 

Customer Address 
    customer_address_id (PK) 
    customer_id (FK) 
    address_id (FK) 
    address_type 

Address 
    address_id (PK) 
    street 
    city 
    state 
    country 
    postal_code 

我有一個地址域類如下:

public class Address { 
    public int Id {get; set;} 
    public int CustomerId {get; set;} 
    public int AddressId {get; set;} 
    public int AddressType {get; set;} 
    public string Street {get; set;} 
    public string City{get; set;} 
    public string State{get; set;} 
    public string Country{get; set;} 
    public string PostalCode{get; set;} 
} 

我想先給代碼試一試,看看我是否可以在保存時拆分Address域類,以便將數據保存到適當的表中。由於CustomerAddress和地址表不共享密鑰,因此這並不那麼直截了當。我能想到的唯一方法是首先創建一組特定於代碼的類,並將其映射回我的Address域類。

有什麼辦法可以實現實體分割而不必創建額外的代碼優先特定類?

+0

你想把地址分成2個表嗎? –

+0

如果'Address'類已經有'CustomerId',爲什麼你需要一個'Customer_Address'表? –

回答

0

你需要的是兩張表之間的關係。你應該如下建模你的表格:

public class CustomerAddress { 
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int Id {get; set;} 

    public int CustomerId {get; set;} 

    [ForeignKey("CustomerId")] 
    public Customer Customer 

    public int AddressId {get; set;} 

    [ForeignKey("AddressId")] 
    public Address Address 

    public int AddressType {get; set;} 
} 

public class Address { 
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public int Id {get; set;} 

    public string Street {get; set;} 

    public string City{get; set;} 

    public string State{get; set;} 

    public string Country{get; set;} 

    public string PostalCode{get; set;} 
} 
相關問題