entity framework - Defining navigation from Person to Country but not from Country to Persons using the Fluent syntax -


i have following relationship between person , country defined convention. works perfectly.

public class person {     public long personid {get; set;}     public string name {get; set;}      public long countryid {get; set;}     public virtual country country {get; set;} }  public class country {     public long countryid {get; set;}     public string name {get; set;} } 

i wish change name of property country else. understand means relationship not work anymore convention. wish define using fluent syntax.

i found this reference not clear me how should handle exact scenario since in examples both sides of relation contain foreign key or collection.

there section "configuring relationship 1 navigation property" makes me think should this:

modelbuilder.entity<patient>()      .hasrequired(t => t.country)      .withrequiredprincipal(); 

however, whenever when storing countries results in following exception

{"the insert statement conflicted foreign key constraint \"fk_dbo.countries_dbo.patients_countryid\". conflict occurred in database \"tests_ffbe7a6e73a747ce8cda71f963bb20b7\", table \"dbo.patients\", column 'patientid'.\r\nthe statement has been terminated."} 

so question now: - how define above 'by convention' relationship using fluent syntax? - countryid property still required when using fluent syntax?

in sample code you're expressing this:

  • entity<patient>().hasrequired(t => t.country): each patient must have related country
  • .withrequiredprincipal(): each country must have related patient

i suppose don't need each country have 1 or more related patients. so, this:

  modelbuilder.entity<person>()               .hasrequired(p => p.country)               .withmany(); 

this means each person must have country, , each country can have many related persons. , don't specify nvaigation country person.

to understand kind of fluent api relationships take account first function (i.e hasrequired) relationship first entity second entity. , then, second function (i.e. withxxx) relationship second entity first one.

thanks fluent api it's easy express kind of relationship without making mistakes. besides there overloads or without paramteres allow specify navigation properties, or omit them if they're not present. example, if needed navigate country persons, using persons property, this:

  withmany(c => c.persons) 

Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -