C# · 12月 26, 2021

c# – 如何处理集合

任何人都可以写迷你指南,解释如何使用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<PostComment> 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<BlogPost> 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等等.

解决方法 以下是我在实体框架核心中使用导航属性的提示.

提示1:初始化集合

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

提示2:使用HasOne和WithMany或HasMany和WithOne方法构建

protected override void OnModelCreating(ModelBuilder model){ model.Entity<Post>() .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();