Entity Framework 1 to 1 relationship using code first. how?

后端 未结 2 461
你的背包
你的背包 2020-12-03 13:25

I have two classes. How can I turn these two classes into a one to one relationship using the entity framework code first method?

public class Region
{
  pu         


        
相关标签:
2条回答
  • 2020-12-03 13:58

    This occurs in CodeFirst because of the virtual keyword. In effect, you are creating a relationship where creating one item requires the creation of the other. however, the virtual keyword allows lazy instantiation, which means that creating an object of one type doesn't automatically create the other type, allowing the Id on the foreign item to be null. This implies a 0..1 relationship, but since each side is virtual, what you get is a 0..0 which isn't allowed.

    There are 2 methods which you can use to remedy the situation.

    1. remove the virtual option from either one side or both sides of the navigation properties, allowing for a 0..1 or a 1..1 map.
    2. explicitly add a property for the Foreign key from the other entity on each object. i.e. on class Region add a property for FactoryId and on Factory add a property for RegionId

    There are other ways to help Entity Framework determine which object is the Dependent Object, i.e. using Entity Framework Fluent api.

    from MSDN

    Configuring a Relationship Where Both Ends Are Required (One-to-One)

    In most cases the Entity Framework can infer which type is the dependent and which is the principal in a relationship. However, when both ends of the relationship are required or both sides are optional the Entity Framework cannot identify the dependent and principal. When both ends of the relationship are required, use WithRequiredPrincipal or WithRequiredDependent after the HasRequired method. When both ends of the relationship are optional, use WithOptionalPrincipal or WithOptionalDependent after the HasOptional method.

    the following code would create a Principal Factory with a Dependent Region

    // Configure the primary key for the Region
    modelBuilder.Entity<Region>()
        .HasKey(t => t.RegionId);
    
    modelBuilder.Entity<Factory>()
        .HasRequired(t => t.Region)
        .WithRequiredPrincipal(t => t.Factory);
    
    0 讨论(0)
  • 2020-12-03 13:59

    EF6, add attributes:

    [Key]
    public int RegionId { get; set; }
    
    [Key, ForeignKey("Region")]
    public int FactoryId { get; set; }
    
    0 讨论(0)
提交回复
热议问题