加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何处理集合

发布时间:2020-12-15 04:05:57 所属栏目:百科 来源:网络整理
导读:任何人都可以写迷你指南,解释如何使用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 ListP
任何人都可以写迷你指南,解释如何使用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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读