自引用
public class PictureCategory { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int CategoryId { get; private set; } public string Name { get; set; } public int? ParentCategoryId { get; private set; } public virtual PictureCategory ParentCategory { get; set; } public virtual ICollectionSubPictureCategories { get; set; } public PictureCategory() { SubPictureCategories = new HashSet (); } } public class PictureCategoryContext : DbContext { public virtual DbSet PictureCategories { get; set; } public PictureCategoryContext() : base("name=DemoContext") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity () .HasKey(p=>p.CategoryId) .HasMany(p => p.SubPictureCategories) .WithOptional(t => t.ParentCategory) .HasForeignKey(t=>t.ParentCategoryId); } }
怎么使用?
private static void Main() { using (var context = new PictureCategoryContext()) { var _1st = new PictureCategory { Name = "第1代" }; var _2st = new PictureCategory { Name = "第2代" }; var _3_1st = new PictureCategory { Name = "第3_1代" }; var _3_2st = new PictureCategory { Name = "第3_2代" }; var _3_3st = new PictureCategory { Name = "第3_3代" }; var _4st = new PictureCategory { Name = "第4代" }; var _5_1st = new PictureCategory { Name = "第5_5_1代" }; var _5_2st = new PictureCategory { Name = "第5_2代" }; _1st.SubPictureCategories = new List{ _2st }; _2st.SubPictureCategories = new List { _3_1st, _3_2st, _3_3st }; _3_3st.SubPictureCategories = new List { _4st }; _4st.SubPictureCategories = new List { _5_1st, _5_2st }; context.PictureCategories.Add(_1st); context.SaveChanges(); } using (var context=new PictureCategoryContext()) { var query = context.PictureCategories.Where(p=>p.ParentCategory==null).ToList(); query.ForEach(t => Print(t,1)); } Console.ReadKey(); } private static void Print(PictureCategory category, int level) { Console.WriteLine("{0}--{1}", category.Name, level); category.SubPictureCategories.ToList().ForEach(t=>Print(t,level+1)); }
效果:
模型如下:
再次我们分析一下该关系模型所涉及到degree, multiplicity, and direction:
degree【度】: 一元multiplicity【复合度,在UML中很常见,也就是重复度】: 0..1和*;因为一个Parent有N个children,而每一个child只能有1个Parent
direction【流向】: 双向
这三个术语详细的介绍看这里
Database relationships are characterized by degree, multiplicity, and direction. Degreeis the number of entity types that participate in the relationship. Unary and binary relationships are the most common. Tertiary and n-place relationships are more theoretical than practical.
Multiplicityis the number of entity types on each end of the relationship. You have seen the multiplicities 0..1 (zero or 1), 1 (one), and * (many).Finally, the directionis either one-way or bidirectional.The Entity Data Model supports a particular kind of database relationship called an Association Type. An Association Type relationship has either unary or binary degree, multiplicities 0..1, 1, or *, and a direction that is bidirectional