asp.net-core - 使用 Include 进行 EF Core 联接,但外键不是另一个表上的主键

标签 asp.net-core entity-framework-core ef-core-2.2

我正在尝试将我的表与另一端的外键和主键相关联。但现在我将使用外键,它不是所述表的主键。我正在使用[InverseProperty],但我认为它有一个错误,因为我已经环顾四周几个小时了,而且所有人都说了同样的事情。

文档表:

public class Document
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DocumentId { get; set; }
    public int ProjectId { get; set; }
    public int DepartmentId { get; set; }
    public int AuthorId { get; set; }

    [NotMapped]
    public virtual User Author { get; set; }
}

用户

public class User
{
    [Key]
    public int UserId { get; set; }
    public int AuthUserId { get; set; }
    public string DisplayName { get; set; }

    [NotMapped]
    [ForeignKey("AuthorId")]
    public virtual Document Document { get; set; }
}

上下文:

modelBuilder.Entity<User>(entity =>
        {
            entity.HasOne(u => u.Document)
            .WithMany("AuthorId");
        });

我正在尝试使用他们的解决方案 here ,但运气不佳。

任何帮助将不胜感激。谢谢!

最佳答案

But now i will be using a ForeignKey which is not the primary for the said table.

为此,您可以使用 EF Core Alternate Keys特征。但首先要更正您的模型类设置,如下所示:(正如您所说,User 将有多个Document)

public class Document
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DocumentId { get; set; }
    public int ProjectId { get; set; }
    public int DepartmentId { get; set; }
    public int AuthorId { get; set; }

    public User Author { get; set; }
}

public class User
{
    [Key]
    public int UserId { get; set; }
    public int AuthUserId { get; set; }
    public string DisplayName { get; set; }


    public ICollection<Document> Documents { get; set; }
}

然后在Fluent API中配置如下:

modelBuilder.Entity<Document>()
        .HasOne(p => p.Author)
        .WithMany(b => b.Documents)
        .HasForeignKey(p => p.AuthorId)
        .HasPrincipalKey(b => b.AuthUserId); // <-- here you are specifying `AuthUserId` as `PrincipalKey` in the relation which is not primary key

关于asp.net-core - 使用 Include 进行 EF Core 联接,但外键不是另一个表上的主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54799285/

相关文章:

azure - 无法访问 EF Core 中生成的 SQL

c# - EF Core EnableSensitiveDataLogging 无法按预期工作

entity-framework-migrations - EF Core 反复创建相同的迁移,更改标识列并且不做任何更改

c# - .net core 应用程序中 ServicePointManager.DefaultConnectionLimit 的最高安全数是多少?

typescript - 无法使用 Visual Studio Code 从 Typescript 访问 C# Controller

SQL Server INSERT 性能(SQL、Azure SQL 数据库)

entity-framework - Entity Framework 核心 2.2 : Disable migrations for specific entities

c# - 从.NET core中的IQueryable获取Sqlite SQL语句

asp.net - 在不使用 TempData 的成功 POST 请求后重定向后显示消息

asp.net-core - 红隼服务器 : How to bind different ports to different controllers?