C# 保存父项时未为相关实体生成Id
我正试图将一个客户保存到我的数据库中,而该客户有几个关系。但当我保存客户时,CustomerManager(一对多)似乎不会自动生成其Id。我得到这个错误: “无法将值NULL插入表'AppDB.dbo.customerManager'的'Id'列;列不允许为NULL。插入失败。\r\n语句已终止。” 我的客户类别及相关数据:C# 保存父项时未为相关实体生成Id,c#,sql-server,entity-framework,C#,Sql Server,Entity Framework,我正试图将一个客户保存到我的数据库中,而该客户有几个关系。但当我保存客户时,CustomerManager(一对多)似乎不会自动生成其Id。我得到这个错误: “无法将值NULL插入表'AppDB.dbo.customerManager'的'Id'列;列不允许为NULL。插入失败。\r\n语句已终止。” 我的客户类别及相关数据: public class Customer { public int Id { get; set; } public string
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public virtual ICollection<CustomerContacts> CustomerContacts { get; set; }
public virtual ICollection<CustomerManager> CustomerManagers { get; set; }
}
public class CustomerContacts
{
public int Id { get; set; }
public string Name { get; set; }
public string EmailAddress { get; set; }
public string PhoneNumber { get; set; }
public int CustomerId { get; set; }
public virtual Customer Customer { get; set; }
}
public class CustomerManager
{
public int Id { get; set; }
public string Name { get; set; }
public string EmailAddress { get; set; }
public string PhoneNumber { get; set; }
public int CustomerId { get; set; }
public virtual Customer Customer { get; set; }
}
然后,我在刚刚运行的同一个存储库中有一个Commit方法DbSet.SaveChanges()代码>
任何帮助都是非常感激的
Martin Johansson确保已在数据库中将Id列设置为Identity。有时我们会犯这样愚蠢的错误。我在迁移时仔细检查了identity是否为true。请确保在数据库中将Id列设置为identity。有时我们会犯这样愚蠢的错误,我在迁移时反复检查身份是否真实。
public void Add(Customer entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State != EntityState.Detached)
{
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(entity);
}
}