如何使用收集工作 [英] How to work with collections

查看:205
本文介绍了如何使用收集工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以写的迷你指南,说明如何使用集合在EF工作?

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

和上下文类:

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方法来写,这样我可以在任何地方我的code使用Posts.Add等?

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

推荐答案

下面是我的秘诀与实体框架的核心导航属性的工作。

Here are my tips for working with navigation properties in 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:构建使用 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:如果您没有急于显式地加载

Tip 4: Explicitly load if you didn't eagerly

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

这篇关于如何使用收集工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆