asp.net - insert one to many code first -


i want insert factor in db , factor have customer id.

i have 2 class

public class customer     {          [key, foreignkey("factor")]         public int id { get; set; }          [required]         public string name { get; set; }          [required]         public string lastname { get; set; }          public gender gender { get; set; }          [required]         public string mobile { get; set; }          public virtual icollection<factor> factor { get; set; }      }      public class factor     {         public int id { get; set; }          [required]         public string name { get; set; }          public datetime date { get; set; }          public virtual customer customer { get; set; }          public virtual icollection<factordetails> factordetails { get; set; }          public virtual factortype factortype { get; set; }      } 

and create modelview these 2 classes,

public class createfactorviewmodel {     public factor factor { get; set; }     public int customerid { get; set; } } 

in create view add new factor , select 1 customer dropdown list. in create controller want add customerid factor customer id

    public actionresult create(createfactorviewmodel model)     {          if (modelstate.isvalid)         {             model.factor.customer = new customer { id = model.customerid };               db.factors.add(model.factor);              db.savechanges();             return redirecttoaction("index");         }          return view();     } 

but error

validation failed 1 or more entities. see 'entityvalidationerrors' property more details.

i know error occurred customer attribute,but don't know how can inset factor base customer id.

can me?

from user question, should declare foreignkey

change class code

    public class factor     {         ...         [foreignkey("customer")]         public int customer_id { get; set; }         ... }    public actionresult create(createfactorviewmodel model)     {          if (modelstate.isvalid)         {              model.factor.customer_id = model.customerid;               db.factors.add(model.factor);              db.savechanges();             return redirecttoaction("index");         }          return view();     } 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -