![](/img/trans.png)
[英]Entity Framework - Code first - One to Many relationship with shared primary key
[英]Entity Framework - Code First - Entity Splitting When There Is No Shared Primary Key
我有一個具有以下表的現有數據庫:
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
我有一個Address域類,如下所示:
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表不共享公共密鑰,因此並非如此。 我能想到的唯一方法是先創建一組特定於代碼的類,然后將其映射回我的Address域類。
有什么方法可以實現實體拆分而無需創建其他代碼優先的特定類?
您需要的是兩個表之間的關系。 您應該按以下方式對表進行建模:
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;}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.