Sto cercando di mettere in relazione le mie tabelle con ForeignKey e PrimaryKey dall'altra parte. Ma ora userò un ForeignKey che non è il primario per il suddetto tavolo. Stavo usando [InverseProperty], ma penso che ci sia un bug con esso dal momento che ho già guardato intorno per ore e tutti dicono la stessa cosa su di esso.
Tabella dei documenti:
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; }
}
utenti
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; }
}
Contesto:
modelBuilder.Entity<User>(entity =>
{
entity.HasOne(u => u.Document)
.WithMany("AuthorId");
});
Sto cercando di usare la soluzione qui , ma senza fortuna.
Qualsiasi aiuto sarebbe molto apprezzato. Grazie!
Ma ora userò un ForeignKey che non è il primario per il suddetto tavolo.
Per fare ciò è possibile utilizzare la funzione Chiavi alternative EF core. Ma prima correggi il tuo modello di classe impostato come segue: (Come hai detto un User
avrà più 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; }
}
Quindi, nella configurazione Fluent API
come segue:
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