5

Sto utilizzando EntityFramework 4.1.Più relazioni uno a molti con Entity Framework

ho il seguente modello:

public class User 
{ 
    [Key] 
    public int Id { get; set; } 
    public string Username { get; set; } 
    public string Password { get; set; } 

    public virtual User Creator { get; set; } 
    public virtual User LastEditor { get; set; } 
} 

Quando provo a generare la mia base di dati ho ottenuto questo errore:

Unable to determine the principal end of an association between the types 'User' and 'User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

Ma ho anche questa classe:

public class Course 
{ 
    [Key] 
    public int Id { get; set; } 
    public string Name { get; set; } 

    public virtual User Creator { get; set; } 
    public virtual User LastEditor { get; set; } 
} 

E funziona bene, ho generato queste chiavi esterne:

Creator_Id 
LastEditor_Id 

Devo aggiungere qualcosa nel mio modello Utente per farlo funzionare?

+0

Date un'occhiata a questa domanda e vedere se si porta nella giusta direzione: http://stackoverflow.com/questions/6531671/what-does-principal-end-of-an-association-significa-in-11-relationship-in-entity-fr – Cyric297

risposta

7

EF prova - per convenzione - per creare una relazione uno-a-uno tra User.Creator e User.LastEditor perché entrambi si riferiscono alla classe User in cui essi stessi si trova nel sono che non è il caso per la classe Course.. Per Course.Creator e Course.LastEditor EF crea due relazioni uno-a-molti su User. Per ottenere lo stesso per le proprietà a User si dovrà configurare le relazioni con API Fluent:

modelBuilder.Entity<User>() 
    .HasOptional(u => u.Creator)  // or HasRequired 
    .WithMany(); 

modelBuilder.Entity<User>() 
    .HasOptional(u => u.LastEditor) // or HasRequired 
    .WithMany(); 
+0

Grazie! Funziona! E bella spiegazione. –

Problemi correlati