5

Używam EntityFramework 4.1.Wiele relacji jeden do wielu z Entity Framework

Mam następujący model:

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

Kiedy próbuję wygenerować mojej bazy danych mam ten błąd:

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.

Ale ja też mam tę klasę:

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

I działa dobrze, mam wygenerowane klucze obce:

Creator_Id 
LastEditor_Id 

Czy muszę coś dodać w moim modelu użytkownika, aby działał?

+0

Spójrz na to pytanie i sprawdzić, czy to prowadzi we właściwym kierunku: http://stackoverflow.com/questions/6531671/what-does-principal-end-of-an-association-means-in-11-relationship-in-entity-fr – Cyric297

Odpowiedz

7

EF stara - umownie - do tworzenia relacji jeden do jednego między User.Creator i User.LastEditor ponieważ oba odnoszą się do klasy User gdzie są sami się w tym nie jest w przypadku klasy Course.. Dla Course.Creator i Course.LastEditor EF tworzy dwie relacje jeden-do-wielu z User. Aby osiągnąć taki sam dla właściwości w User trzeba będzie skonfigurować relacji z Fluent API:

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

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

Dzięki! To działa! I miłe wyjaśnienie. –