EF Core Join using Include but ForeignKey is not Primary Key on the other table

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

Question

I am trying to relate my Tables with ForeignKey and PrimaryKey on the other end. But now i will be using a ForeignKey which is not the primary for the said table. I was using [InverseProperty] but i think there's a bug with it since i've been looking around for hours already and all of them says the same thing about it.

Documents Table:

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; }
}

Users

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; }
}

Context:

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

I am trying to use the solution they here, but no luck.

Any help would really be appreciated. Thanks!

1
0
2/21/2019 4:53:47 AM

Accepted Answer

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

To do this you can use EF Core Alternate Keys feature. But first correct your model class set up as follows: (As you said a User will have multiple 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; }
}

Then in the Fluent API configuration as follows:

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
1
2/21/2019 4:49:12 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow