实体框架:将对象保存到不同的实体

时间:2016-04-18 14:24:11

标签: c# entity-framework

我很难解决这个问题......基本上我有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远离其他部门?任何帮助,将不胜感激。提前谢谢!

2 个答案:

答案 0 :(得分:1)

你需要让EF知道你有多对多的关系。目前EF看到一对多。

您可以将ICollection<Department>添加到Location或者将其配置为流利。

文档:Configure Many-to-Many relationship:

答案 1 :(得分: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,它们将处理部门和地点之间的多对多关系。

相关问题