Friday 15 June 2012

c# - Entity framework multiple composite keys, cascade on delete -



c# - Entity framework multiple composite keys, cascade on delete -

i'm having bit of problem configuring composite keys in entity framework between 3 tables, code first approach. have base of operations class has id, of classes inherit from. first table has collection of sec table items, while has collection of 3rd table. need composite keys cascade on delete when removing element either table. using aggregate root pattern.

public abstract class baseclass { [key, column(order = 0)] [databasegenerated(databasegeneratedoption.identity)] public long id { get; set; } } public class table1 : baseclass { public virtual icollection<table2> table2collection { get; set; } public string name { get; set; } } public class table2 : baseclass { public table1 table1 {get; set;} [key, foreignkey("table1"), column(order=1)] public long table1id { get; set; } public virtual icollection<table3> table3collection { get; set; } public string name { get; set; } } public class table3 : baseclass { [key, foreignkey("table2id,table1id"), column(order = 1)] public table2 table2 { get; set; } public long table2id{ get; set; } public long table1id{ get; set; } public string name { get; set; } }

the code above works fine when delete element of type either table 1 or table2, won't allow me delete element table3 giving me next exception:

"the relationship not changed because 1 or more of foreign-key properties non-nullable.when alter made relationship, related foreign-key property set null value. if foreign-key not back upwards null values, new relationship must defined, foreign-key property must assigned non-null value, or unrelated object must deleted."

bellow model builder:

protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.entity<table2>() .hasrequired(x=>x.table1) .withmany(x =>x.table2collection) .willcascadeondelete(true); modelbuilder.entity<table3>() .hasrequired(x=>x.table2) .withmany(x =>x.table3collection) .willcascadeondelete(true); }

i suspect may have not configured model builder properly, can't seem figure out how configure allow deleting element of type table3. help appreciated.

figured out missing. i'm putting reply here might bump same problem have. needed create fk pk fk (since don't allow null). it's bit annoying since if have more complex tree, number of keys you'd have manage of grow deeper go.

modelbuilder.entity<table3>().haskey(m => new {m.id, m.table2id, m.table1id});

if has thought on how shorten number of keys manage please leave answer. since might not best solution.

c# entity-framework ef-code-first composite-key

No comments:

Post a Comment