EF Code First:将子实体添加到新实体

时间:2011-11-25 13:25:10

标签: entity-framework-4.1 ef-code-first

我目前正在尝试将我们的模型从edmx迁移到Code First,但是在为数据库播种方面遇到了一些麻烦。

我有这些(简化的)实体:

public class EntityBase
{
    public EntityBase()
    {
        this.OfficeEntities = new HashSet<OfficeEntity>();
    }

    [Key]
    public int Id { get; set; }

    public ICollection<OfficeEntity> OfficeEntities { get; set; }
}

public class Office : EntityBase
{
    public Office()
    {
        this.EntityCollection = new HashSet<OfficeEntity>();
    }

    public ICollection<OfficeEntity> EntityCollection { get; set; }
}

public class Employee : EntityBase
{
    // misc properties not in use by the associatio in this example
}

public class OfficeEntity
{
    [Key]
    public int Id { get; set; }
    public int OfficeEntityPositions { get; set; }
    public int OfficeId { get; set; }
    public int EntityBaseId { get; set; }

    public Office Office { get; set; }
    public EntityBase Entity { get; set; }
}

我在尝试播种数据库时使用这些实体:

var office = new Office();
var employees = GenerateEmployees(); // A method that simply creates a list of new employee objects
foreach (var employee in employees)
{
    office.EntityCollection.Add(new OfficeEntity {Entity = employee, OfficeEntityPositions = 1});
}

DbContext.SaveChanges();

这只会将新的办公室实体添加到数据库中,其他一切都被遗漏(Employees和OfficeEntitites)。当谈到FK关系时,数据库模式中的一切看起来都很好。

这似乎发生在我的数据库种子的其他地方,在那里我创建新实体并向其中添加新的子对象,其中只添加了父项:S

有关如何解决这个问题的想法吗?

0 个答案:

没有答案