我如何 link 三个不同的管理员用户访问一篇文章?

How can I link three different admin-users to an article?

在我的 CMS/CRM-system 中,Article-class 有三个 AdminUser 属性,一个用于 "created by",一个用于 "edited by" 和一个 "published by":

public class Article
{
    public int Id { get; set; }
    // some more properties ...
    public AdminUser CreatedBy { get; set; }
    public AdminUser EditedBy { get; set; }
    public AdminUser PublishedBy { get; set; }
}

AdminUser-class:

public class AdminUser
{
    public int Id { get; set; }
    public int MemberId { get; set; }
    // some more properties ...
    public Member Member { get; set; }
}

Member-class只是包含姓名等个人信息。在我的系统中,并非所有成员都是管理员,但所有管理员都是成员。)

当我在 AdminUser-class 中没有任何对 Article 的引用时,这工作正常。但是如果我想知道管理员创建、编辑或发布的文章的任何信息,它们必须是 AdminUser-class:

的一部分
public class AdminUser
{
    public int Id { get; set; }
    // ... and the rest of the properties
    public List<Article> CreatedArticles { get; set; }
    public List<Article> EditedArticles { get; set; }
    public List<Article> PublishedArticles { get; set; }
}

现在,当我尝试 add-migration 时,我收到以下错误消息:

Unable to determine the relationship represented by navigation property 'AdminUser.Articles' of type 'List'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

我有点明白发生了什么,但我不知道如何"manually configure the relationship"。

或者你可以在你的 sql 中添加一个 table 叫做 author 然后给它 ( id , author.Id, author_job, article_id) 然后在工作中你可以决定那个作者对文章做了什么

您需要分配 AdminUserArticle 之间的关系。您可以使用 Has/With pattern 配置与 Fluent API 的关系。在您的 dbcontext 中,添加关系:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<AdminUser>()
      .HasMany(c => c.EditedArticles)
      .WithOne(e => e.EditedBy);

    modelBuilder.Entity<AdminUser>()
    .HasMany(c => c.CreatedArticles)
    .WithOne(e => e.CreatedBy);


    modelBuilder.Entity<AdminUser>()
    .HasMany(c => c.PublishedArticles)
    .WithOne(e => e.PublishedBy);
}

创建您的 Article Fluent API 配置如下:

public class ArticleConfiguration : IEntityTypeConfiguration<Article>
{
    public void Configure(EntityTypeBuilder<Article> builder)
    {
        builder.HasOne(a => a.CreatedBy).WithMany(au => au.CreatedArticles);
        builder.HasOne(a => a.EditedBy).WithMany(au => au.EditedArticles);
        builder.HasOne(a => a.PublishedBy).WithMany(au => au.PublishedArticles);
    }
}

然后在DbConetxtOnModelCreating如下:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);
     modelBuilder.ApplyConfiguration(new ArticleConfiguration());
}