实体框架 - 创建新子(多个)时重复父(一个)

时间:2013-03-09 10:47:12

标签: entity-framework

因为我的英语不好,所以我直截了当。 为何记录公司在数据库中创建新记录和客户记录是否参考新公司记录? 感谢您的帮助:)

public class Company : EntityBase
{
    public string Name { get; set; }

    public List<Customer> Customers { get; set; }
    public List<Invoice> Invoices { get; set; }
}

public class Customer : EntityBase
{
    public string Name { get; set; }

    public Company Company { get; set; }
    public List<Card> Cards { get; set; }
}

public class EFRepositoryBase<TEntity> where TEntity : class, IEntity, new()
{
    protected IUnitOfWork UnitOfWork { get; set; }

    protected BenzineFleetContext Context
    {
        get { return (BenzineFleetContext) UnitOfWork; }
    }

    public virtual DbSet<TEntity> GetDbSet<TEntity>() where TEntity : class
    {
        return Context.Set<TEntity>();
    }

    public virtual void Add(TEntity entity)
    {
        GetDbSet<TEntity>().Add(entity);
    }

    public virtual void SaveChanges()
    {
        Context.SaveChanges();
    }
}

    //Save

var cus = new Customer {Company = SelectedCompany}

    _srv.Add(cus);
    _srv.SaveChanges();

2 个答案:

答案 0 :(得分:14)

当您通过DbSet<T>.Add方法添加实体时,实体及其所有尚未在上下文中引用的实体将在ChangeTracker中标记为Added。这就是为什么要添加新公司(看起来公司没有附加到上下文):

var customer = new Customer {Company = SelectedCompany}
context.Customers.Add(customer);
// at this point customer state will be Added
// company state also will be Added
context.SaveChanges();

要避免此类行为,请在添加新客户之前将公司附加到上下文:

var customer = new Customer {Company = SelectedCompany}
context.Companies.Attach(SelectedCompany);
context.Customers.Add(customer);
// at this point customer state will be Added
// company state will be Unchanged (if you haven't change it)
context.SaveChanges();

另一种方法是手动维护状态:

var customer = new Customer {Company = SelectedCompany}
context.Customers.Add(customer);
context.Entry(SelectedCompany).State = EntityState.Unchanged;
// at this point customer state will be Added
// company state will be Unchanged
context.SaveChanges();

答案 1 :(得分:-2)

您可以在实体框架中查看所有基本 CRUD(创建读取更新删除)操作的thisthis。这对你很有帮助。您还可以简要了解外键基础和一对多关系。