不同的DbContext之间一对多

时间:2018-06-20 21:40:22

标签: c# entity-framework asp.net-identity entity-framework-core

有两个实体:用户(帖子的作者)和帖子

public class ApplicationUser : IdentityUser<int>
{
    public virtual IEnumerable<Post> Posts { get; set; }
}

public class Post
{
    public int Id { get; set; }
    public int AuthorId { get; set; }
    public virtual ApplicationUser Author { get; set; }
}

还有两个DbContext

public class AppIdentityContext : IdentityDbContext<ApplicationUser, IdentityRole<int>, int>
{
    public AppIdentityContext(DbContextOptions<AppIdentityContext> options) : base(options) { }
}

public class ForumContext : DbContext
{
    public ForumContext(DbContextOptions<ForumContext> options) : base(options) { }

    public DbSet<Post> Posts { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Post>(ConfigurePost);
    }

    private void ConfigurePost(EntityTypeBuilder<Post> builder)
    {
        // Author is ApplicationUser from AppIdentityContext
        // As far as I know, this won't work
        builder.HasOne(p => p.Author)
            .WithMany(u => u.Posts)
            .HasForeignKey(p => p.AuthorId);
    }
}

在这种情况下,我可以通过某种方式用EF Core配置自动填充Post.Author字段吗?

P.S。我发现了这一点(似乎是解决方案),但我不明白。
https://github.com/aspnet/EntityFrameworkCore/issues/4595#issuecomment-189534388

0 个答案:

没有答案