实体框架 - 代码优先 - 没有共享主键时实体拆分

时间:2016-02-12 07:51:08

标签: c# .net entity-framework ef-code-first code-first

我有一个包含以下表格的现有数据库:

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表不共享公共密钥,因此不是那么简单。我能想到的唯一方法是首先创建一组特定于代码的类,然后将其映射回我的地址域类。

有没有什么方法可以实现实体拆分而无需创建额外的代码优先特定类?

1 个答案:

答案 0 :(得分: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;}
}