【问题标题】:Entity Framework - Code First - Entity Splitting When There Is No Shared Primary Key实体框架 - 代码优先 - 没有共享主键时的实体拆分
【发布时间】:2016-05-23 07:02:09
【问题描述】:

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

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;}
}

我想尝试代码优先,看看是否可以在保存时拆分地址域类,以便将数据持久保存到适当的表中。由于 CustomerAddress 和 Address 表不共享一个公共键,所以这不是那么简单。我能想到的唯一方法是首先创建一组特定于代码的类并将其映射回我的地址域类。

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

【问题讨论】:

  • 你想把地址分成2个表吗?
  • 如果Address 类已经有CustomerId,为什么还需要Customer_Address 表?

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


【解决方案1】:

您需要的是两个表之间的关系。您应该如下建模您的表:

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;}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 2013-01-15
    • 2016-10-17
    相关资源
    最近更新 更多