如何使用集合 [英] How to work with collections
本文介绍了如何使用集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能编写一个解释如何在 EF 中使用集合的迷你指南?
Can anyone write mini-guide which explains how to work with collections in 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 等?
What do I need to write in OnModelCreating method so that I can use Posts.Add and etc. everywhere in my code?
推荐答案
以下是我在 Entity Framework Core 中使用导航属性的技巧.
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
构建> 方法
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);
}
提示 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屋!
查看全文