I have the following relationship: Tables relationship
And the following classes (Only the relevant properties):
- Affair: (AffairID, Title, ... , AffairsGroups)
- Group: (GroupID, Name, ... , AffairsGroups)
- AffairsGroups(AffairID, GroupID, Affairs, Groups)
I want to add a new Affair record to the database which will be also added to the AffairsGroups table (With known GroupID) I've tried it the following way:
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;
}
But i get the following exception:
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'.
These are my context classes: 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; }
}
What am i doing wrong? Thanks