EF7外键,级联和限制

时间:2016-01-31 10:48:05

标签: entity-framework entity-framework-core

尝试学习如何在EF7中建模关系以及如何使用外键,这些是我简化的模型

public class User
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        //..
        public virtual List<BlogPost> BlogPosts { get; set; }
        public virtual List<Comment> Comments { get; set; }
    }

public class BlogPost
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int BlogPostId { get; set; }
        //...

        public int UserId { get; set; }
        public virtual User User { get; set; }

        public virtual List<Comment> Comments { get; set; }

    }

  public class Comment
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CommentId { get; set; }
        //..

        public int BlogPostId { get; set; }
        public virtual BlogPost BlogPost { get; set; }

        public int UserId { get; set; }
        public virtual User User { get; set; }
    }
  • UserOne to Many
  • Comments的关系
  • UserOne to Many
  • BlogPosts的关系
  • BlogPostOne to One
  • User的关系
  • BlogPostOne to Many
  • Comment的关系
  • CommentOne to One
  • User的关系
  • CommentOne to One
  • BlogPost的关系
  • 当我删除User时,CommentsBlogPosts应该是BlogPost 使用相关的FK
  • 删除
  • 当我删除Comments时,应使用相关的FK删除所有protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Comment>(). HasOne(p => p.User). WithMany(p => p.Comments). OnDelete(Microsoft.Data.Entity.Metadata.DeleteBehavior.Restrict). HasForeignKey(p => p.UserId); modelBuilder.Entity<Comment>(). HasOne(p => p.BlogPost). WithMany(p => p.Comments). OnDelete(Microsoft.Data.Entity.Metadata.DeleteBehavior.Restrict). HasForeignKey(p => p.BlogPostId); modelBuilder.Entity<User>(). HasMany(p => p.Comments). WithOne(p => p.User). OnDelete(Microsoft.Data.Entity.Metadata.DeleteBehavior.Cascade). HasForeignKey(p => p.CommentId); modelBuilder.Entity<User>(). HasMany(p => p.BlogPosts). WithOne(p => p.User). OnDelete(Microsoft.Data.Entity.Metadata.DeleteBehavior.Cascade). HasForeignKey(p => p.BlogPostId); modelBuilder.Entity<BlogPost>(). HasOne(p => p.User). WithMany(p => p.BlogPosts). HasForeignKey(p => p.UserId). OnDelete(Microsoft.Data.Entity.Metadata.DeleteBehavior.Restrict); modelBuilder.Entity<BlogPost>(). HasMany(p => p.Comments). WithOne(p => p.BlogPost). OnDelete(Microsoft.Data.Entity.Metadata.DeleteBehavior.Cascade). HasForeignKey(p => p.CommentId); }

所以我把上面的内容翻译成了这个

INSTALLED_APPS

但这看起来打字太多了,我还无法在Entity Framework 7上找到好的文档。我的问题是,如果我上面提到的点数,我做了什么不必要的事情,我可以输入更少但仍然可以获得我提到了什么?

0 个答案:

没有答案