1. 程式人生 > >初試 Entity Framework Core 的多對多映射

初試 Entity Framework Core 的多對多映射

include pan top output args first with spa 提問

今天在博問中看到一個關於 EF Core 的提問 ef core 2.0 多對多查詢的問題,由於還沒使用過 EF Core 的多對多映射,於是參考 EF Core 幫助文檔快速寫了個 .net core 控制臺程序(基於 EF Core In-Memory Database)實驗了一下。

實體類的定義:

1)Post

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    
public List<PostTag> PostTags { get; set; } }

2)Tag

public class Tag
{
    public int TagId { get; set; }
    public string TagName { get; set; }

    public List<PostTag> PostTags { get; set; }
}

3)PostTag

public class PostTag
{
    public int PostId { get; set; }
    
public Post Post { get; set; } public int TagId { get; set; } public Tag Tag { get; set; } }

DbContext 的定義與映射配置:

public class MyDbContext : DbContext
{
    public DbSet<Post> Posts { get; set; }
    public DbSet<Tag> Tags { get; set; }

    public MyDbContext(DbContextOptions<MyDbContext> options)
        : 
base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<PostTag>() .HasKey(t => new { t.PostId, t.TagId }); modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Post) .WithMany(p => p.PostTags) .HasForeignKey(pt => pt.PostId); modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Tag) .WithMany(t => t.PostTags) .HasForeignKey(pt => pt.TagId); } }

控制臺程序 Main 方法:

class Program
{
    static async Task Main(string[] args)
    {
        IServiceCollection services = new ServiceCollection();
        services.AddDbContext<MyDbContext>(options =>
        {
            options.UseInMemoryDatabase("blog_sample");
        });

        IServiceProvider sp = services.BuildServiceProvider();

        var writeDbContext = sp.GetService<MyDbContext>();

        var post = new Post
        {
            Title = "test title",
            Content = "test body",
            PostId = 1
        };
        writeDbContext.Add(post);

        var tag = new Tag
        {
            TagId = 2,
            TagName = "efcore"
        };
        writeDbContext.Add(tag);

        var postTag = new PostTag
        {
            PostId = 1,
            TagId = 2
        };
        writeDbContext.Add(postTag);
        writeDbContext.SaveChanges();

        var readDbContext = sp.GetService<MyDbContext>();
        post = await readDbContext.Posts.FirstOrDefaultAsync();
        Console.WriteLine(post.PostTags.FirstOrDefault().Tag.TagId); 
        //output is 2
    }
}

查詢時連 Include 都不需要,EF Core 會自動打理好一切。

初試 Entity Framework Core 的多對多映射