gpt4 book ai didi

entity-framework - Entity Framework - 创建新子项(多个)时重复父项(一个)

转载 作者:行者123 更新时间:2023-12-03 07:40:58 26 4
gpt4 key购买 nike

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

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();

最佳答案

当您通过 DbSet<T>.Add 添加实体时方法,然后实体及其引用的所有尚未在上下文中的实体将被标记为 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();

关于entity-framework - Entity Framework - 创建新子项(多个)时重复父项(一个),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15309835/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com