One or Zero to One Entity Framework Code First FluentApi

后端 未结 2 1905
醉酒成梦
醉酒成梦 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 EntityTwoNavigation { get; set; }
    }
    
    public class EntityTwo
    {
        [Key]
        public int EntityTwoId { get; set; }
        public int EntityOneId { get; set; }
    
        [ForeignKey("EntityOneId")]
        public EntityOne EntityOne { get; set; }
    }
    

提交回复
热议问题