Utilizzo del nuovo finale RC1 di ASP.NET Core ed Entity Framework 7.0. Ho due campi con una relazione uno-a-molti tra Standard e Studenti. Se ho solo l'FK e la chiave di navigazione, il codice funziona bene, ma quando aggiungo il secondo FK (Standard2) e il campo Nav (Studenti2) ottengo il seguente messaggio di errore: InvalidOperationException: la navigazione 'Studenti' sul tipo di entità 'TestProject.Models.Standard' non è stato aggiunto al modello, o ignorato, o targetType di destinazione ignorato.
public class Standard
{
public Standard()
{
}
public int StandardId { get; set; }
public string StandardName { get; set; }
public IList<Student> Students { get; set; }
public IList<Student> Students2 { get; set; }
}
public Student()
{
}
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime DateOfBirth { get; set; }
public byte[] Photo { get; set; }
public decimal Height { get; set; }
public float Weight { get; set; }
//Foreign key for Standard
public int StandardId { get; set; }
public int StandardId2 { get; set; }
[ForeignKey("StandardId")]
public Standard Standard { get; set; }
[ForeignKey("StandardId2")]
public Standard Standard2 { get; set; }
}
Come posso avere due FK nella stessa tabella in EF 7?
Il problema è che devi specificare l'altra estremità delle tue relazioni usando InverseProperty
attributo InverseProperty
, qualcosa che EF non può dedurre da solo e quindi lancia un'eccezione:
public class Standard
{
public int StandardId { get; set; }
public string StandardName { get; set; }
[InverseProperty("Standard")]
public IList<Student> Students { get; set; }
[InverseProperty("Standard2")]
public IList<Student> Students2 { get; set; }
}
Oppure puoi ottenere gli stessi risultati usando l'API fluente:
modelBuilder.Entity<Standard>()
.HasMany(s => s.Students)
.WithOne(s => s.Standard)
.HasForeignKey(s => s.StandardId);
modelBuilder.Entity<Standard>()
.HasMany(s => s.Students2)
.WithOne(s => s.Standard2)
.HasForeignKey(s => s.StandardId2);