8

因为我的英文不好,我就直接开门见山了。为什么在数据库中记录公司创建新记录而客户记录引用新公司记录?感谢帮助 :)

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 = 新客户 {Company = SelectedCompany}

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

2 回答 2

15

当您通过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();

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

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();
于 2013-03-09T11:19:56.150 回答
-2

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

于 2013-03-09T11:26:38.657 回答