谁能写迷你指南来解释如何在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等?

最佳答案

这是我在Entity Framework Core中使用导航属性的提示。

提示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:使用HasOneWithManyHasManyWithOne方法进行构建
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();

09-10 00:45
查看更多