How to handle cascade delete in many-to-many relationship in Entity Framework
I have three entities: Boss
, Employee
, and Instruction
. Bosses have a set of Instructions they can issue (one-to-many relationship) and Bosses have a set of Employees (one-to-many relationship) they can give those instructions to. An instruction can be given to more than one Employee, so there is a many-to-many relationship between Employees and Instructions. So here's my entities:
public class Boss
{
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Instruction> Instructions { get; set; }
public ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public int ID { get; set; }
public int BossID { get; set; }
public string Name { get; set; }
public DateTime WorkTime { get; set; }
public ICollection<Instruction> Instructions { get; set; }
}
public class Instruction
{
public int ID { get; set; }
public string Name { get; set; }
public int BossID { get; set;}
public ICollection<Employee> Employees { get; set; }
}
The goal is to write queries to get lists of a Boss's Employees, and also to see what Employees are assigned to each Instruction. An additional reason for modeling it this way is so that we can enforce uniqueness constraints so that, for example, we don't have the same Employee entered multiple times, and maybe we don't want a Boss to schedule multiple Employees to work at the same time. So here's the DbContext with those relationships mapped with Fluent API:
public class Model1 : DbContext
{
public Model1() : base("name=Model1") { }
public virtual DbSet<Boss> Bosses { get; set; }
public virtual DbSet<Instruction> Instructions { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Entity<Employee>().HasMany<Instruction>(x => x.Instructions).WithMany(x => x.Employees);
modelBuilder.Entity<Boss>().HasMany<Instruction>(x => x.Instructions);
modelBuilder.Entity<Boss>().HasMany<Employee>(x =>x.Employees);
modelBuilder.Entity<Employee>().Property(x => x.BossID)
.HasColumnAnnotation(IndexAnnotation.AnnotationName,
new IndexAnnotation(new IndexAttribute("OneEmployeeAtATime", 0) { IsUnique = true }));
modelBuilder.Entity<Employee>().Property(x => x.WorkTime)
.HasColumnAnnotation(IndexAnnotation.AnnotationName,
new IndexAnnotation(new IndexAttribute("OneEmployeeAtATime", 1) { IsUnique = true }));
base.OnModelCreating(modelBuilder);
}
}
The line modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
is in there because otherwise I get a "multiple cascade paths" error. The behavior I want is when I delete a Boss
it should delete his Employees
and Instructions
as well, but if I delete either an Instruction
or an Employee
it should not cascade. But when I run my test:
using (Model1 db = new Model1())
{
Boss boss = db.Bosses.First();
db.Bosses.Remove(boss);
db.SaveChanges();
}
I get this error message:
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.EmployeeInstructions_dbo.Employees_Employee_ID". The conflict occurred in database "Model1", table "dbo.EmployeeInstructions", column 'Employee_ID'.
The statement has been terminated.
Am I missing something in the Fluent API?
c# entity-framework entity-framework-6
add a comment |
I have three entities: Boss
, Employee
, and Instruction
. Bosses have a set of Instructions they can issue (one-to-many relationship) and Bosses have a set of Employees (one-to-many relationship) they can give those instructions to. An instruction can be given to more than one Employee, so there is a many-to-many relationship between Employees and Instructions. So here's my entities:
public class Boss
{
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Instruction> Instructions { get; set; }
public ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public int ID { get; set; }
public int BossID { get; set; }
public string Name { get; set; }
public DateTime WorkTime { get; set; }
public ICollection<Instruction> Instructions { get; set; }
}
public class Instruction
{
public int ID { get; set; }
public string Name { get; set; }
public int BossID { get; set;}
public ICollection<Employee> Employees { get; set; }
}
The goal is to write queries to get lists of a Boss's Employees, and also to see what Employees are assigned to each Instruction. An additional reason for modeling it this way is so that we can enforce uniqueness constraints so that, for example, we don't have the same Employee entered multiple times, and maybe we don't want a Boss to schedule multiple Employees to work at the same time. So here's the DbContext with those relationships mapped with Fluent API:
public class Model1 : DbContext
{
public Model1() : base("name=Model1") { }
public virtual DbSet<Boss> Bosses { get; set; }
public virtual DbSet<Instruction> Instructions { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Entity<Employee>().HasMany<Instruction>(x => x.Instructions).WithMany(x => x.Employees);
modelBuilder.Entity<Boss>().HasMany<Instruction>(x => x.Instructions);
modelBuilder.Entity<Boss>().HasMany<Employee>(x =>x.Employees);
modelBuilder.Entity<Employee>().Property(x => x.BossID)
.HasColumnAnnotation(IndexAnnotation.AnnotationName,
new IndexAnnotation(new IndexAttribute("OneEmployeeAtATime", 0) { IsUnique = true }));
modelBuilder.Entity<Employee>().Property(x => x.WorkTime)
.HasColumnAnnotation(IndexAnnotation.AnnotationName,
new IndexAnnotation(new IndexAttribute("OneEmployeeAtATime", 1) { IsUnique = true }));
base.OnModelCreating(modelBuilder);
}
}
The line modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
is in there because otherwise I get a "multiple cascade paths" error. The behavior I want is when I delete a Boss
it should delete his Employees
and Instructions
as well, but if I delete either an Instruction
or an Employee
it should not cascade. But when I run my test:
using (Model1 db = new Model1())
{
Boss boss = db.Bosses.First();
db.Bosses.Remove(boss);
db.SaveChanges();
}
I get this error message:
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.EmployeeInstructions_dbo.Employees_Employee_ID". The conflict occurred in database "Model1", table "dbo.EmployeeInstructions", column 'Employee_ID'.
The statement has been terminated.
Am I missing something in the Fluent API?
c# entity-framework entity-framework-6
I don't have a definitive answer but a thought: are there any Instructions in the database that point at Employees who now report to a different Boss? If that can happen you could have a cascaded delete to an Instruction that is still associated with an Employee that is no longer part of the cascaded Employee deletions for that Boss.
– sellotape
Nov 28 '18 at 18:31
add a comment |
I have three entities: Boss
, Employee
, and Instruction
. Bosses have a set of Instructions they can issue (one-to-many relationship) and Bosses have a set of Employees (one-to-many relationship) they can give those instructions to. An instruction can be given to more than one Employee, so there is a many-to-many relationship between Employees and Instructions. So here's my entities:
public class Boss
{
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Instruction> Instructions { get; set; }
public ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public int ID { get; set; }
public int BossID { get; set; }
public string Name { get; set; }
public DateTime WorkTime { get; set; }
public ICollection<Instruction> Instructions { get; set; }
}
public class Instruction
{
public int ID { get; set; }
public string Name { get; set; }
public int BossID { get; set;}
public ICollection<Employee> Employees { get; set; }
}
The goal is to write queries to get lists of a Boss's Employees, and also to see what Employees are assigned to each Instruction. An additional reason for modeling it this way is so that we can enforce uniqueness constraints so that, for example, we don't have the same Employee entered multiple times, and maybe we don't want a Boss to schedule multiple Employees to work at the same time. So here's the DbContext with those relationships mapped with Fluent API:
public class Model1 : DbContext
{
public Model1() : base("name=Model1") { }
public virtual DbSet<Boss> Bosses { get; set; }
public virtual DbSet<Instruction> Instructions { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Entity<Employee>().HasMany<Instruction>(x => x.Instructions).WithMany(x => x.Employees);
modelBuilder.Entity<Boss>().HasMany<Instruction>(x => x.Instructions);
modelBuilder.Entity<Boss>().HasMany<Employee>(x =>x.Employees);
modelBuilder.Entity<Employee>().Property(x => x.BossID)
.HasColumnAnnotation(IndexAnnotation.AnnotationName,
new IndexAnnotation(new IndexAttribute("OneEmployeeAtATime", 0) { IsUnique = true }));
modelBuilder.Entity<Employee>().Property(x => x.WorkTime)
.HasColumnAnnotation(IndexAnnotation.AnnotationName,
new IndexAnnotation(new IndexAttribute("OneEmployeeAtATime", 1) { IsUnique = true }));
base.OnModelCreating(modelBuilder);
}
}
The line modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
is in there because otherwise I get a "multiple cascade paths" error. The behavior I want is when I delete a Boss
it should delete his Employees
and Instructions
as well, but if I delete either an Instruction
or an Employee
it should not cascade. But when I run my test:
using (Model1 db = new Model1())
{
Boss boss = db.Bosses.First();
db.Bosses.Remove(boss);
db.SaveChanges();
}
I get this error message:
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.EmployeeInstructions_dbo.Employees_Employee_ID". The conflict occurred in database "Model1", table "dbo.EmployeeInstructions", column 'Employee_ID'.
The statement has been terminated.
Am I missing something in the Fluent API?
c# entity-framework entity-framework-6
I have three entities: Boss
, Employee
, and Instruction
. Bosses have a set of Instructions they can issue (one-to-many relationship) and Bosses have a set of Employees (one-to-many relationship) they can give those instructions to. An instruction can be given to more than one Employee, so there is a many-to-many relationship between Employees and Instructions. So here's my entities:
public class Boss
{
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Instruction> Instructions { get; set; }
public ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public int ID { get; set; }
public int BossID { get; set; }
public string Name { get; set; }
public DateTime WorkTime { get; set; }
public ICollection<Instruction> Instructions { get; set; }
}
public class Instruction
{
public int ID { get; set; }
public string Name { get; set; }
public int BossID { get; set;}
public ICollection<Employee> Employees { get; set; }
}
The goal is to write queries to get lists of a Boss's Employees, and also to see what Employees are assigned to each Instruction. An additional reason for modeling it this way is so that we can enforce uniqueness constraints so that, for example, we don't have the same Employee entered multiple times, and maybe we don't want a Boss to schedule multiple Employees to work at the same time. So here's the DbContext with those relationships mapped with Fluent API:
public class Model1 : DbContext
{
public Model1() : base("name=Model1") { }
public virtual DbSet<Boss> Bosses { get; set; }
public virtual DbSet<Instruction> Instructions { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Entity<Employee>().HasMany<Instruction>(x => x.Instructions).WithMany(x => x.Employees);
modelBuilder.Entity<Boss>().HasMany<Instruction>(x => x.Instructions);
modelBuilder.Entity<Boss>().HasMany<Employee>(x =>x.Employees);
modelBuilder.Entity<Employee>().Property(x => x.BossID)
.HasColumnAnnotation(IndexAnnotation.AnnotationName,
new IndexAnnotation(new IndexAttribute("OneEmployeeAtATime", 0) { IsUnique = true }));
modelBuilder.Entity<Employee>().Property(x => x.WorkTime)
.HasColumnAnnotation(IndexAnnotation.AnnotationName,
new IndexAnnotation(new IndexAttribute("OneEmployeeAtATime", 1) { IsUnique = true }));
base.OnModelCreating(modelBuilder);
}
}
The line modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
is in there because otherwise I get a "multiple cascade paths" error. The behavior I want is when I delete a Boss
it should delete his Employees
and Instructions
as well, but if I delete either an Instruction
or an Employee
it should not cascade. But when I run my test:
using (Model1 db = new Model1())
{
Boss boss = db.Bosses.First();
db.Bosses.Remove(boss);
db.SaveChanges();
}
I get this error message:
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.EmployeeInstructions_dbo.Employees_Employee_ID". The conflict occurred in database "Model1", table "dbo.EmployeeInstructions", column 'Employee_ID'.
The statement has been terminated.
Am I missing something in the Fluent API?
c# entity-framework entity-framework-6
c# entity-framework entity-framework-6
asked Nov 28 '18 at 17:58
MatthewMatthew
2,05911027
2,05911027
I don't have a definitive answer but a thought: are there any Instructions in the database that point at Employees who now report to a different Boss? If that can happen you could have a cascaded delete to an Instruction that is still associated with an Employee that is no longer part of the cascaded Employee deletions for that Boss.
– sellotape
Nov 28 '18 at 18:31
add a comment |
I don't have a definitive answer but a thought: are there any Instructions in the database that point at Employees who now report to a different Boss? If that can happen you could have a cascaded delete to an Instruction that is still associated with an Employee that is no longer part of the cascaded Employee deletions for that Boss.
– sellotape
Nov 28 '18 at 18:31
I don't have a definitive answer but a thought: are there any Instructions in the database that point at Employees who now report to a different Boss? If that can happen you could have a cascaded delete to an Instruction that is still associated with an Employee that is no longer part of the cascaded Employee deletions for that Boss.
– sellotape
Nov 28 '18 at 18:31
I don't have a definitive answer but a thought: are there any Instructions in the database that point at Employees who now report to a different Boss? If that can happen you could have a cascaded delete to an Instruction that is still associated with an Employee that is no longer part of the cascaded Employee deletions for that Boss.
– sellotape
Nov 28 '18 at 18:31
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53525443%2fhow-to-handle-cascade-delete-in-many-to-many-relationship-in-entity-framework%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53525443%2fhow-to-handle-cascade-delete-in-many-to-many-relationship-in-entity-framework%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I don't have a definitive answer but a thought: are there any Instructions in the database that point at Employees who now report to a different Boss? If that can happen you could have a cascaded delete to an Instruction that is still associated with an Employee that is no longer part of the cascaded Employee deletions for that Boss.
– sellotape
Nov 28 '18 at 18:31