繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM