我有以下关系: 表关系
以及以下类(仅相关属性):
- Affair: (AffairID, Title, ... , AffairsGroups)
- 组:(GroupID,名称,...,事务组)
- 事务组(AffairID、GroupID、事务、组)
我想向数据库中添加一条新的 Affair 记录,该记录也将添加到 AffairsGroups 表中(使用已知 GroupID)我已经尝试过以下方式:
private Boolean addAffairToDatabase(Affair affair)
{
AffairDal affairContext = new AffairDal();
affairContext.Affairs.Add(affair);
affairContext.SaveChanges();
AffairsGroupDal affairsGroupContext = new AffairsGroupDal();
affairsGroupContext.AffairsGroups.Add(new AffairsGroup{ AffairID = affair.AffairID , GroupID = user.GroupID});
affairsGroupContext.SaveChanges();
return true;
}
但我得到以下异常:
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.AffairsGroups_dbo.Affairs_AffairID". The conflict occurred in database "NuixTest.DAL.AffairsGroupDal", table "dbo.Affairs", column 'AffairID'.
这些是我的上下文类: 1。
public class AffairDal: DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Affair>().ToTable("Affairs");
}
public DbSet<Affair> Affairs { get; set; }
}
2.
public class AffairsGroupDal: DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<AffairsGroup>().ToTable("AffairsGroups");
}
public DbSet<AffairsGroup> AffairsGroups { get; set; }
}
我究竟做错了什么?谢谢