2012-01-31 7 views
6

mam ten model i konfiguracjęjednostka po raz pierwszy kod framework - Unia z dwóch pól w jednej kolekcji

public class Person 
{ 
    public int? FatherId { get; set; } 
    public virtual Person Father { get; set; } 
    public int? MotherId { get; set; } 
    public virtual Person Mother { get; set; } 
    public virtual List<Person> Childs { get; set; } 

} 
class PersonConfiguration : EntityTypeConfiguration<Person> 
{ 
    public PersonConfiguration() 
    { 
     HasOptional(e => e.Father).WithMany(e => e.Childs) 
       .HasForeignKey(e => e.FatherId); 
     HasOptional(e => e.Mother).WithMany(e => e.Childs) 
       .HasForeignKey(e => e.MotherId); 
    } 
} 

i ja dostać ten błąd, gdzie typ jest początkowy.

Podany schemat jest nieprawidłowy. Błędy: (151,6): error 0040: Type Person_Father nie jest zdefiniowany w przestrzeni nazw ExamModel (Alias ​​= Self).

Czy istnieje sposób na mapowanie właściwości Childs według obu właściwości (motherId i fatherId)?

Odpowiedz

14

Nie można odwzorować dwóch właściwości nawigacyjnych na jedną właściwość kolekcji. Wygląda wyśmiewa ale trzeba mieć dwie właściwości zbierania

public class Person 
{ 
    public int? FatherId { get; set; } 
    public virtual Person Father { get; set; } 
    public int? MotherId { get; set; } 
    public virtual Person Mother { get; set; } 
    public virtual List<Person> ChildrenAsFather { get; set; } 
    public virtual List<Person> ChildrenAsMother { get; set; } 
} 

class PersonConfiguration : EntityTypeConfiguration<Person> 
{ 
    public PersonConfiguration() 
    { 
     HasOptional(e => e.Father).WithMany(e => e.ChildrenAsFather) 
       .HasForeignKey(e => e.FatherId); 
     HasOptional(e => e.Mother).WithMany(e => e.ChildrenAsMother) 
       .HasForeignKey(e => e.MotherId); 
    } 
} 
2

Dziękuję Eranga, odpowiedź jest dokładnie to, co potrzebne!

Dodatkowo, tutaj jest kod modelBuilder, jeśli ktokolwiek używa tej metody zamiast metody konfiguracji, której użyła Eranga.

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<Person>(). 
    HasKey(i => i.PersonId); 

    modelBuilder.Entity<Person>(). 
    HasOptional(f => f.Father). 
    WithMany(f => f.ChildrenAsFather). 
    HasForeignKey(f => f.FatherId); 

    modelBuilder.Entity<Person>(). 
    HasOptional(m => m.Mother). 
    WithMany(m => m.ChildrenAsMother). 
    HasForeignKey(m => m.MotherId); 
} 
Powiązane problemy