2012-01-31 11 views
6

tôi có mô hình này và cấu hìnhthực thể đang khuôn khổ đầu tiên - Liên minh của hai lĩnh vực thành một bộ sưu tập

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

và tôi nhận được lỗi này, nơi loại là ban đầu.

Giản đồ được chỉ định không hợp lệ. Lỗi: (151,6): lỗi 0040: Loại Person_Father không được định nghĩa trong không gian tên ExamModel (Bí danh = Tự).

Có cách nào để ánh xạ Childs thuộc tính của cả hai thuộc tính (motherId và fatherId)?

Trả lời

14

Không thể ánh xạ hai thuộc tính điều hướng đến một thuộc tính bộ sưu tập duy nhất. Có vẻ như chế nhạo nhưng bạn phải có hai thuộc tính bộ sưu tập

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

Cảm ơn bạn, Eranga, câu trả lời của bạn chính xác là những gì tôi cần!

Ngoài ra, đây là mã modelBuilder nếu có ai đó đang sử dụng phương thức đó thay vì phương pháp cấu hình mà Eranga đã sử dụng.

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