同理市的ParentId是省的Id皇冠现金app

View
Code

譬喻:城市库,有国家、省、市…,省的ParentId是国家的Id,同理市的ParentId是省的Id

 运转调节台程序

皇冠现金app,View
Code

在实质上的连串项支出出中,可能会超过一样张表同期保留自身和顶头上司(或下属)的新闻(一般是通过安装贰个上级主键【ParentId】的列与主键【Id】关系)

皇冠现金app 1

皇冠现金app 2皇冠现金app 3

皇冠现金app 4皇冠现金app 5

View
Code

下一场查看数据库:

皇冠现金app 6

static void Main(string[] args)
        {

            var country = new City {  Name="中国" };
            var province = new City { Name = "广东省" };
            var citys = new List<City>
            {
                new City { Name="广州" },
                new City { Name="深圳" },
                new City { Name="珠海" }
            };
            province.ChildCitys = citys;
            country.ChildCitys = new List<City> { province };
            EFContext<City> context = new EFContext<City>();
            context.Table.Add(country);
            context.SaveChanges();
            Console.WriteLine("ok");
            Console.ReadKey();
        }

 

public class City
    {
        /// <summary>
        /// Id
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 上级Id
        /// </summary>
        public int? ParentId { get; set; }
        /// <summary>
        /// 下级地区
        /// </summary>
        public virtual ICollection<City> ChildCitys { get; set; }
        /// <summary>
        /// 上级地区
        /// </summary>
        public virtual City Parent { get; set; }
    }

 示例使用的是Entity Framework
6.X,同一时间上边的涉嫌是0..1←→N,因为国家并未有上级(ParentId为null)

public class CityMap : EntityTypeConfiguration<City>
    {
        public CityMap()
        {
            ToTable("City");
            HasKey(c => c.Id);
            Property(c => c.Id).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
            Property(c => c.Name).HasMaxLength(50);

            //配置关系
            HasMany(c => c.ChildCitys).WithOptional(c => c.Parent).HasForeignKey(k => k.ParentId);
        }
    }

皇冠现金app 7

皇冠现金app 8皇冠现金app 9