EntityFrameworkCore实现复杂数据关系绑定

csharp

浏览数:982

2019-1-8

片段 1片段 2


DbContext

    public class LifeDbContext : DbContext
    {
        public LifeDbContext(DbContextOptions options) : base(options)
        {
        }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<t_palace>().HasQueryFilter(t => t.f_del_flag == false).HasKey(t => t.f_id);
            //自联表
            //一个palace表有多个palace表子集t_palaces;一个palace表有一个palace表父级t_parent_palace;关联外键f_parent_id
            builder.Entity<t_palace>().HasMany(t => t.t_palaces).WithOne(t => t.t_parent_palace).HasForeignKey(t => t.f_parent_id);

            builder.Entity<t_follow>().HasQueryFilter(t => t.f_del_flag == false).HasKey(t => t.f_id);
            builder.Entity<t_user>().HasQueryFilter(t => t.f_del_flag == false).HasKey(t => t.f_id);
            //多外键关联表(user两次关联follow)
            //一个user表有多个follow表子集t_follows;一个follow表有一个user表父级t_user;关联外键f_user_id
            builder.Entity<t_user>().HasMany(t => t.t_follows).WithOne(t => t.t_user).HasForeignKey(t => t.f_user_id);
            //一个user表有多个follow表子集t_target_follows;一个follow表有一个user表父级t_target_user;关联外键f_target_user_id
            builder.Entity<t_user>().HasMany(t => t.t_target_follows).WithOne(t => t.t_target_user).HasForeignKey(t => t.f_target_user_id);

            base.OnModelCreating(builder);
        }

        public DbSet<t_palace> t_palace { get; set; }
        public DbSet<t_follow> t_follow { get; set; }
        public DbSet<t_user> t_user { get; set; }

    }


Entity

    /// <summary>
    /// 用户
    /// </summary>
    public class t_user
    {
        [Key]
        public Guid f_id { get; set; }

        /// <summary>
        /// 手机号
        /// </summary>
        [Display(Name = "手机号"), MaxLength(20, ErrorMessage = "{0}的长度不可超过{1}")]
        public string f_phone { get; set; }

        public virtual ICollection<t_follow> t_follows { get; set; }

        public virtual ICollection<t_follow> t_target_follows { get; set; }

    }

    
    /// <summary>
    /// 用户关注
    /// </summary>
    public class t_follow
    {
        [Key]
        public Guid f_id { get; set; }

        public Guid f_target_user_id { get; set; }
        public Guid f_user_id { get; set; }

        [ForeignKey("f_user_id")]
        public virtual t_user t_user { get; set; }

        [ForeignKey("f_target_user_id")]
        public virtual t_user t_target_user { get; set; }

    }

    
    /// <summary>
    /// 宫殿
    /// </summary>
    public class t_palace
    {
        [Key]
        public Guid f_id { get; set; }

        /// <summary>
        /// 父级(null为第一级)
        /// </summary>
        public Guid? f_parent_id { get; set; }

        [ForeignKey("f_parent_id")]
        public virtual t_palace t_parent_palace { get; set; }

        public virtual ICollection<t_palace> t_palaces { get; set; }

    }