如何使用集合

neo*_*ash 9 c# entity-framework entity-framework-core

任何人都可以写迷你指南,解释如何使用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; }
}
Run Code Online (Sandbox Code Playgroud)

和上下文类:

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);

    }
}
Run Code Online (Sandbox Code Playgroud)

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

bri*_*lam 17

以下是我在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; }        
}
Run Code Online (Sandbox Code Playgroud)

技巧2:建立一个使用HasOneWithManyHasManyWithOne方法

protected override void OnModelCreating(ModelBuilder model)
{
    model.Entity<Post>()
        .HasMany(p => p.Comments).WithOne(c => c.Post)
        .HasForeignKey(c => c.PostId);
}
Run Code Online (Sandbox Code Playgroud)

提示3:急切加载集合

var posts = db.Posts.Include(p => p.Comments);
Run Code Online (Sandbox Code Playgroud)

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

db.Comments.Where(c => c.PostId == post.Id).Load();
Run Code Online (Sandbox Code Playgroud)