我很难解决这个问题......基本上我有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; }
}
每当我尝试创建一个部门并为其添加一个位置时,Location会获得一个名为Department_ID
的新属性,我想这是我所有邪恶的根源。因此,如果我添加Location1
ID = 1
而另一Location2
添加ID = 2
,则两个地点都会添加Department_ID = 1
(或其他整数...)。但是,如果我尝试将Location1
添加到新创建的部门,该部门将会“偷”&#34;该位置来自其他部门LocationList
,我猜测它是因为Department_ID changes
。我该怎么做?所以它没有Location1
远离其他部门?任何帮助,将不胜感激。提前谢谢!
答案 0 :(得分:1)
你需要让EF知道你有多对多的关系。目前EF看到一对多。
您可以将ICollection<Department>
添加到Location
或者将其配置为流利。
答案 1 :(得分:1)
您的Location
和Department
课程之间的关系很多。意思是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
表,其中包含两列:DepartmentId
和LocationId
,它们将处理部门和地点之间的多对多关系。