自反关联的EFCore实现注意事项

  • Post author:
  • Post category:其他


这样一个类图,在映射到代码的时候(使用EFCore),如何解决1:1的问题。

直接映射出代码,编译会出错的,需要在OnModelCreating,这样:

modelBuilder.Entity<Floor>()

.HasOne(x => x.Below)

.WithOne(y => y.Upper);

否则报错:

The dependent side could not be determined for the one-to-one relationship between ‘Floor.Below’ and ‘Floor.Upper’. To identify the dependent side of the relationship, configure the foreign key property. If these navigations should not be part of the same relationship, configure them independently via separate method chains in ‘OnModelCreating’. See http://go.microsoft.com/fwlink/?LinkId=724062 for more details.

类实现:

    public class Floor
    {
        [Key]
        public int Id { get; set; }

        /// <summary>
        /// 层名
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 层高
        /// </summary>
        public double Height { get; set; }

        /// <summary>
        /// 所属建筑
        /// </summary>
        public Building Building { get; set; }

        /// <summary>
        /// 楼层类型
        /// </summary>
        public FloorType Type { get; set; }

        /// <summary>
        /// 包含的结构体
        /// </summary>
        public List<Structure> Structures { get; set;}

        /// <summary>
        /// 下一层
        /// </summary>
        [ForeignKey("Id")]
        public int BelowId { get; set; }

        /// <summary>
        /// 下一层
        /// </summary>
        public Floor Below { get; set; }

        /// <summary>
        /// 上一层
        /// </summary>
        [ForeignKey("Id")]
        public int UpperId { get; set; }

        /// <summary>
        /// 上一层
        /// </summary>

        public Floor Upper { get; set; }
    }



版权声明:本文为bdbox原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。