Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Can anyone write mini-guide which explains how to work with collections in EF?

For example I have following models:

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

And context class:

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

    }
}

What do I need to write in OnModelCreating method so that I can use Posts.Add and etc. everywhere in my code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
110 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here are my tips for working with navigation properties in Entity Framework Core.

Tip 1: Initialize collections

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

Tip 2: Build using the HasOne and WithMany or HasMany and WithOne methods

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

Tip 3: Eagerly load the collection

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

Tip 4: Explicitly load if you didn't eagerly

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...