尝试学习如何在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; }
}
User
与One to Many
Comments
的关系
User
与One to Many
BlogPosts
的关系
BlogPost
与One to One
User
的关系
BlogPost
与One to Many
Comment
的关系
Comment
与One to One
User
的关系
Comment
与One to One
BlogPost
的关系
User
时,Comments
和BlogPosts
应该是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上找到好的文档。我的问题是,如果我上面提到的点数,我做了什么不必要的事情,我可以输入更少但仍然可以获得我提到了什么?