Entity Framework - Code First - 没有共享主键时的实体拆分
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
我有一个地址域 class 如下:
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;}
}
我想尝试代码优先,看看我是否可以在保存时拆分地址域 class,以便将数据保存到适当的表中。由于 CustomerAddress 和 Address 表不共享公共键,因此这不是那么简单。我能想到的唯一方法是首先创建一组特定于代码的 classes 并将其映射回我的地址域 class.
有什么方法可以实现实体拆分而无需创建额外的代码优先特定 classes?
您需要的是两个表之间的关系。您应该按如下方式对表进行建模:
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;}
}
我有一个包含下表的现有数据库:
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
我有一个地址域 class 如下:
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;}
}
我想尝试代码优先,看看我是否可以在保存时拆分地址域 class,以便将数据保存到适当的表中。由于 CustomerAddress 和 Address 表不共享公共键,因此这不是那么简单。我能想到的唯一方法是首先创建一组特定于代码的 classes 并将其映射回我的地址域 class.
有什么方法可以实现实体拆分而无需创建额外的代码优先特定 classes?
您需要的是两个表之间的关系。您应该按如下方式对表进行建模:
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;}
}