c# - Entity Framework 1-1 relationship: "The navigation property was not found on the dependent type " -


i'm trying define 1:1 relationship in entity framework 6, code first. i've followed tutorial: http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

in example, 1 customer can have 1 specific address. regarding 1:1 relationships i've read , have no idea what's correct way define type of relationship. so, here classes:

public class customer {     public int customerid { get; set; }     public string customername { get; set; }     public address address { get; set; } }  public class address {     [foreignkey("customer")]     public int addressid { get; set; }     public string addressname { get; set; } } 

here initialization:

list<address> addresses = new list<address> {     new address { addressname = "12 main st., houston tx 77001" },     new address { addressname = "1007 mountain dr., gotham ny 10286" } };  list<customer> customers = new list<customer> {     new customer { customername = "john doe", address = addresses.elementat(0) },     new customer { customername = "bruce wayne", address = addresses.elementat(1) } }; customers.foreach(c => context.customer.add(c)); context.savechanges(); 

as can see, i'm not inserting addresses directly, via customer objects. correct way implement 1:1 relationship?

anyway, when deploy application, error:

an exception of type 'system.invalidoperationexception' occurred in entityframework.dll not handled in user code

additional information: foreignkeyattribute on property 'addressid' on type 'aspdotnetmvc.models.address' not valid. navigation property 'customer' not found on dependent type

what wrong here? i'm following tutorial letter.

for specifying dependent , principle in database model relation can use fluntapi method map relations, example:

override method form context class:

  protected override void onmodelcreating(dbmodelbuilder modelbuilder)   {       base.onmodelcreating(modelbuilder);       modelbuilder.entity<customer>()           .hasoptional(x => x.address)           .withrequired(c => x.customer)           .willcascadeondelete(true);   } 

your address model address.cs:

public class address {   public int addressid { get; set; }   public string addressname { get; set; }   public customer cutomer {get;set;} } 

after insert codes on application add migration , update database.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -