c# - EF6 creates new entity instead of setting just a reference -


i'd save list of flags each event. in order done i'm using following method in controller:

 public actionresult createevent(models.event newevent)  {      if(!string.isnullorempty(request.form["flag"]))      {          string[] idarr = request.form["flag"].split(',');          foreach(string idstring in idarr)          {              int id = idstring.toint32();              newevent.flags.add(_applicantrepository.getflagbyid(id));          }      }      _applicantrepository.saveevent(newevent);  } 

in applicantrepository use following methods:

 public void saveevent(event ev)  {      using (var dbctx = new visitorregistrationcontext())      {          dbctx.events.addorupdate(ev);          dbctx.savechanges();      }  }   public models.flag getflagbyid(int id)  {      using (var dbctx = new visitorregistrationcontext())      {          models.flag flag = dbctx.flags.find(id);          return flag;      }  } 

unfortunately, each time save event new flags created. though exist (with same id).

enter image description here

these models:

public class event {     public event()     {         users = new list<usr>();         type = new eventtype();         flags = new list<flag>();     }      public int id { get; set; }      [required]     [display(name = "event")]     public string eventname { get; set; }     public string comment { get; set; }      [required]     public eventtype type { get; set; }     public icollection<flag> flags { get; set; } } 

and

public class flag {     public int id { get; set; }     public string name { get; set; }     public string description { get; set; }     public bool isinactive { get; set; }      public virtual icollection<event> events { get; set; }   } 

how can tell ef simple set reference in intermediate table called flagevent?

you need use same context, example:

public void createevent(event newevent) {     var flags = "1,2,3";     string[] idarr = flags.split(',');     using (var ctx = new context())     {         foreach (string idstring in idarr)             newevent.flags.add(ctx.getflagbyid(convert.toint32(idstring)));         ctx.events.addorupdate(newevent);         ctx.savechanges();     } } 

Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -