One or Zero to One Entity Framework Code First FluentApi

后端 未结 2 1884
醉酒成梦
醉酒成梦 2021-01-05 05:12
  1. I need to create fluentapi one or zero to one reference and have navigation properties on both of entities.
  2. EntityTwo should contain simple proerty to sto

相关标签:
2条回答
  • 2021-01-05 05:47

    The only way I've come up with to handle this is, which is admittedly somewhat ugly, is creating a collection and a helper property to represent the one/zero side. Data annotations included for clarity.

    public class EntityOne
    {
        [Key]
        public int EntityOneId { get; set; }
    
        public EntityTwo EntityTwo => EntityTwoNavigation?.FirstOrDefault();
        public ICollection<EntityTwo> EntityTwoNavigation { get; set; }
    }
    
    public class EntityTwo
    {
        [Key]
        public int EntityTwoId { get; set; }
        public int EntityOneId { get; set; }
    
        [ForeignKey("EntityOneId")]
        public EntityOne EntityOne { get; set; }
    }
    
    0 讨论(0)
  • 2021-01-05 06:03

    In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal. When configuring one-to-one relationships, Entity Framework requires that the primary key of the dependent also be the foreign key. The proper way to achieve what you want could be this, but is using Data Annotations:

    public class EntityOne
    {
      public int Id { get; set; }
      public virtual EntityTwo EntityTwo { get; set; }
    }
    
     public class EntityTwo
     {
       [Key, ForeignKey("EntityOne")]
       public int EntityOneId { get; set; }
       public virtual EntityOne EntityOne { get; set; }
    }
    

    I suggest you check this link, you can find there more info about how work the one-to-one relationships in EF Code First.

    Update:

    I am afraid that what you want is not possible.You can't create a one-to-one relation with a FK that is not declared as a PK. If you want to have each Entities with their own Id an configure an one-to-one relationship between that two entities, then delete the FK property in the EntityTwo.

    My recomendation is map that relationship using Fluent Api as I show below:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<EntityTwo>()
            .HasRequired(et => et.EntityOne)
            .WithOptional(eo=>eo.EntityTwo);
    }
    

    Or you can just add the Required attribute over the navigation property that is principal, for example:

    public class EntityTwo
    {
      public int Id { get; set; }
      // public int EntityOneId { get; set; }
      [Required]
      public EntityOne EntityOne { get; set; }
    }
    
    0 讨论(0)
提交回复
热议问题