How to add entity with one to one association in Entity Framework Code first approach? -


i using ef 4.4 + code first.

i trying add chartofaccount entity dbcontext company's key filled, ask me fill company's companyname @ validation. thought dbcontext associate company me, instead of trying add new company?

    public class chartofaccount: masterdata     {         public chartofaccount()         {             company = new company();             category1 = new accountcatagory();             category2 = new accountcatagory();         }          [key]         [required]         public string code { get; set; }          public virtual company company { get; set; }          [required]         public string accountname { get; set; }          [required]         [stringlength(3)]         public string accountcurrency { get; set; }          public virtual accountcatagory category1 { get; set; }          public virtual accountcatagory category2 { get; set; }          public string reference { get; set; }          public bool hastransaction { get; set; }       }  public class company : masterdata     {         [key]         public int id { get; set; }          [required]         public string companyname { get; set; }          [required]         datetime currentaccountperiod { get; set; }          [required]         [stringlength(3)]         public string basecurrencycode { get; set; }     } 

sadly, primary key of related entity isn't enough. need round trip database obtain entity in same data context.

example:

var company = db.company.single(d => d.id == id); chartofaccounttoadd.company = company; db.chartofaccount.add(chartofaccounttoadd); db.submitchanges(); 

that create relationship existing company.

edit:

i forgot when answered. edit chartofaccount model contain foreign key company like:

    public class chartofaccount: masterdata     {          {rest of model}          public int companyid { get; set; }      } 

and set foreign key new int property. entity framework create relationship without issues. don't set company property on model.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -