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

yov*_*ayz 8 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
Run Code Online (Sandbox Code Playgroud)

var cus = new Customer {Company = SelectedCompany}

    _srv.Add(cus);
    _srv.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

Ser*_*kiy 14

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

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();
Run Code Online (Sandbox Code Playgroud)

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

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();
Run Code Online (Sandbox Code Playgroud)

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

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();
Run Code Online (Sandbox Code Playgroud)