如何在EF4中向父级添加新的子实体?

时间:2011-10-24 17:37:10

标签: c# entity-framework .net-4.0 entity-framework-4 poco

我正在使用VS2010,.NET 4.0,Entity Framework 4和POCO实体。我试图从父母添加和删除子实体。我在[用户]和[公司]之间有多对多的关系。所以我有以下实体:

// Objects created by POCO template generator
public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public ICollection<Company> Companies { get; set; }
}
public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<User> Users { get; set; }
}

在代码的这一点上,用户存在,但有ZERO公司。我想要做的是向用户添加一个新的子公司。此代码可以保存公司,但它也会创建一个重复的用户父级。

public UserRepository
{
    internal ObjectContextEntities _dbContext = new ObjectContextEntities();
    public User Save(User pocoObject)
    {
        // Load the existing User which has no companies
        var loadedEntity = _dbContext.Users.Where(m => m.Id == pocoObject.Id).FirstOrDefault();

        // Add the new company from a POCO object
        loadedEntity.Companies.Add(pocoObject.Companies.Last());

        _dbContext.SaveChanges();
    }
}

我应该如何添加子实体? (没有创建重复的关系?)...还有一种简单的方法来在父用户上执行“ApplyCurrentValues()”时更新这些子项吗?

2 个答案:

答案 0 :(得分:1)

此代码确实有效,不会创建重复的用户。

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public ICollection<Company> Companies { get; set; }

    public User()
    {
        Companies = new List<Company>();
    }
}

public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class POCOEntitiesContext : ObjectContext
{
    private ObjectSet<User> users;
    public ObjectSet<User> Users
    {
        get { return users; }
    }

    private ObjectSet<Company> companies;
    public ObjectSet<Company> Companies
    {
        get { return companies; }
    }

    public POCOEntitiesContext() : base("name=POCOEntities", "POCOEntitiesContainer")
    {
        users = CreateObjectSet<User>();
        companies = CreateObjectSet<Company>();
    }
}

using (var ctx = new POCOEntitiesContext())
{
    var loadedUser = ctx.Users.Where(u => u.Username == "Peri").First();
    loadedUser.Companies.Add(new Company() { Name = "New Company" });
    ctx.SaveChanges();
}

答案 1 :(得分:0)

我尝试了一种更简化的方法,我想出来了:

    var newCompany = pocoObject.Companies.Last();
    newCompany.Users = null;
    loadedUser.Companies.Add(newCompany);

事实证明,因为有一个对孩子的父母INSIDE的引用,它正在传播并导致创建一个新的父母。因此,从POCO的角度来看,我不得不删除父级并将其保留为一个非常简单的对象。 (或者我可以在edmx中删除Child的Parent引用)。但即使这样也会让我的生活变得更轻松:

    loadedUser.Companies.Add(new Company() { Name = "New Company" });