c# - Fluent API not cascading on delete in a one-to-one relationship -
i have 2 classes:
public class student { public long studentid { get; set; } public studentdetails details { get; set; } } public class studentdetails { public long studentdetailsid { get; set; } public student student{ get; set; } //other properties }
one student contains 1 studentdetails. studentdetails can not exist without corresponding student.
with these mappings:
public studentmapping() { this.totable("student"); this.haskey(x => x.studentid); this.hasrequired(x => x.details) .withrequireddependent(x => x.student) .willcascadeondelete(true); } public studentdetailsmapping() { this.totable("studentdetails"); this.haskey(x => x.studentdetailsid); this.hasrequired(x => x.student); }
however, when go database in sql management studio, , following: delete students studentid == 1
, student row gets deleted, delete not cascade studentdetails row. what's going wrong? trying studentdetails row deleted when delete it's student parent object.
have checked this , this article on msdn?
as can see, model not real one-on-one relationship because 2 entities have here doesn't share same primary key.
when model relationship are, in fact, creating one-to-many table structure in database: how can prevent studentdetailsid not in use student? mean, can enforce business rule, strictly db speaking there no rule.
if want enforce cascade delete ef in one-to-one, need make this:
public class student { public long studentid { get; set; } public studentdetails details { get; set; } } public class studentdetails { public long studentid { get; set; } public student student{ get; set; } //other properties } public studentmapping() { this.totable("student"); this.haskey(x => x.studentid); this.hasrequired(x => x.details) .withrequireddependent(x => x.student) .willcascadeondelete(true); } public studentdetailsmapping() { this.totable("studentdetails"); this.haskey(x => x.studentid); this.hasrequired(x => x.student); }
hope helps :)
Comments
Post a Comment