如何使用集合

任何人都可以编写迷你指南,解释如何在EF中使用集合吗?

例如,我有以下模型:

public class BlogPost { public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public DateTime DateTime { get; set; } public List Comments { get; set; } } public class PostComment { public int Id { get; set; } public BlogPost ParentPost { get; set; } public string Content { get; set; } public DateTime DateTime { get; set; } } 

和上下文类:

 public class PostContext : DbContext { public DbSet Posts { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Posts;Trusted_Connection=True;MultipleActiveResultSets=true"); } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); } } 

我需要在OnModelCreating方法中编写什么才能在代码中的任何地方使用Posts.Add等?

以下是在Entity Framework Core中使用导航属性的技巧。

提示1:初始化集合

 class Post { public int Id { get; set; } // Initialize to prevent NullReferenceException public ICollection Comments { get; } = new List(); } class Comment { public int Id { get; set; } public string User { get; set; } public int PostId { get; set; } public Post Post { get; set; } } 

技巧2:使用HasOneWithManyHasManyWithOne方法构建

 protected override void OnModelCreating(ModelBuilder model) { model.Entity() .HasMany(p => p.Comments).WithOne(c => c.Post) .HasForeignKey(c => c.PostId); } 

提示3:急切加载集合

 var posts = db.Posts.Include(p => p.Comments); 

提示4:如果你没有急切地明确加载

 db.Comments.Where(c => c.PostId == post.Id).Load(); 

看来, Comments导航属性无法正常工作。 尝试向BlogPost模型提供PostComment表的实际referencig字段。 同时在PostComments中重命名导航属性以获得EF命名合规性。

 public class BlogPost { public int Id { get; set; } public string Title { get; set; } public string Content { get; set; } public DateTime DateTime { get; set; } public int PosCommentId {get; set; } public List PostComments { get; set; } } 

如果这不起作用,则必须手动定义您的关系,但在此之前的帮助中,您最好在数据库中提供这两个表的模式。

更新01:

第一个提示:您正在使用单数命名表。 这不符合EF命名约定。 必须关闭多元化。 只需将此行放在OnModelCreating方法中即可。

 modelBuilder.Conventions.Remove(); 

第二个提示:我以前的建议是完全错误的,不再考虑它 ,只需使用您的旧模型架构。 现在,假设评论与post之间存在一对多的关系:

 protected override void OnModelCreating(ModelBuilder builder) { modelBuilder.Conventions.Remove(); modelBuilder.Entity().HasRequired(c => c.ParentPost) .WithMany(p => p.Comments); base.OnModelCreating(builder); } 

对于更多信息:

EF一对多关系教程

关系和导航属性

使用Fluent API配置关系

只是为了添加来自@FabioCarello和@bricela的答案,我建议在导航属性上使用虚拟关键字:

 public virtual ICollection { get; set; } 

这将允许延迟加载 ,这意味着只有在第一次调用时才加载集合/引用,而不是在第一次数据检索期间加载。 这对于避免例如递归引用上的堆栈溢出非常有用。

除了您需要非标准行为(如明确要求不可为空的引用)之外,对于像您这样的简单的一对多关系,不需要Fluent

您还可以明确使用外键 ,这对您来说只需要其ID时就不必加载父

 public class PostComment { public int Id { get; set; } public BlogPost ParentPost { get; set; } // // public int? ParentPostId { get; set; } // // public string Content { get; set; } public DateTime DateTime { get; set; } }