c# - How can I make an Optional 1:1 Relationship in EF6 with the same Entity Type on both sides? -


i want donut optionally relate donut, , if so, other donut relate back. i've read, believe need set parent/child relationship, though in real world, it's optional pairing (donuts can exist happily, or exist in pairs). here current setup:

public class donut {      public int id { get; set; }     public int? parentdonutid { get; set; }     public int? childdonutid { get; set; }      // virtual properties     public virtual donut parentdonut { get; set; }     public virtual donut childdonut { get; set; } } 

this statement in mapping file gets me close, insists on creating new key named parentdonut_id on table instead of using existing parentdonutid:

this.hasoptional(t => t.childdonut)             .withoptionalprincipal(t => t.parentdonut); 

but when try mapping:

this.hasoptional(t => t.childdonut)             .withoptionalprincipal(t => t.parentdonut)             .map(m => m.mapkey("parentdonutid")); // or "childdonutid" 

i error message when trying add-migration:

parentdonutid: name: each property name in type must unique. property name 'parentdonutid' defined.

how should set relationship? possible? seems logical enough me, maybe it's 1 of these things db's don't let do?

edit: came across hack, allow me need, doesn't allow navigating backwards child parent donut, nice have:

this.hasoptional(t => t.childdonut)             .withmany() // haxx             .hasforeignkey(t => t.childdonutid); 

what if map both sides? think should work:

 modelbuilder.entity<donut>()         .hasoptional(e => e.childdonut)         .withmany()         .hasforeignkey(t => t.childdonutid);   modelbuilder.entity<donut>()         .hasoptional(e => e.parentdonut)         .withmany()         .withmany(t => t.parentdonutid); 

to understand more self-referencing take @ thread second self-to-self relationship in entity framework


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -