2016-04-18 129 views
1

我很難與這個問題...基本上我有2個類,部門和位置。部門有ICollection的位置,但位置沒有DepartmentID(因爲位置不是唯一的一個部門,同一位置可以添加到不同的部門或不同的表格)。實體框架:將對象保存到不同的實體

public class Department 
{ 
    public Department() 
    { 
     this.LocationList = new HashSet<Location>(); 
     this.JobList = new HashSet<Job>(); 
    } 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Description { get; set; } 
    public string Code { get; set; } 
    public virtual ICollection<Location> LocationList { get; set; } 
    public virtual ICollection<Job> JobList { get; set; } 

} 


public class Location 
    { 

     public int id { get; set; } 
     public string Name { get; set; } 
     public string Adress { get; set; } 

    } 

每當我試圖創建部門和位置添加到它,位置得到一個名爲Department_ID新的屬性,它(我想?)是我所有罪惡的根源。所以,如果我加Location1ID = 1和另一個Location2ID = 2,那麼這兩個位置將有Department_ID = 1(或另一個整數...)。但是,如果我嘗試將Location1添加到新創建的部門,該部門將「竊取」來自其他部門的LocationList的位置,我猜測這是因爲Department_ID changes。我怎麼做到的?所以它不需要Location1遠離其他部門?任何幫助,將不勝感激。提前致謝!

+0

你檢查了你的數據庫,看看它是如何建模的?它看起來像你需要閱讀關於M到N relatioship,並獲得其他表爲了這個工作。 –

+0

這是多對多的關係。我認爲在地點課上你必須有一個部門的集合? – Amine

+0

檢查你的設計,正如你所做的解釋,位置必須有一個部門的集合,而不是該部門有一個集合的位置。 – MNF

回答

1

LocationDepartment等級之間的關係是多對多。這意味着Location可以與多個Department相關,並且Department可以與多個Location相關。
定義一個新的屬性爲您Location類:

public Location() 
{ 
    this.Departments = new HashSet<Department>(); 
} 

public virtual ICollection<Department> Departments { get; set; } 

然後在你的情況下,用流利的映射來確定適當的關係:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<Department>() 
      .HasMany<Location>(s => s.Locations) 
      .WithMany(c => c.Departments) 
      .Map(cs => 
        { 
         cs.MapLeftKey("DepartmentId"); 
         cs.MapRightKey("LocationId"); 
         cs.ToTable("DepartmentsLocations"); 
        }); 

} 

這將在數據庫中創建DepartmentsLocations表有兩列:DepartmentIdLocationId它將處理部門和位置之間的多對多關係。