c# - Entity Framework : many to many relationship , Insert and update -


i have news entity , news based on newsid. defined new entity , group , want news based on group id. tried handle (many many) relationships using this articleby using code first approach.

enter image description here

so in context added :

 public class groupnews : dbcontext     {          public dbset<group> group { get; set; }         public dbset<news> news { get; set; }          public groupnews()             : base("mydb")         {         }          public int newsid { get; set; }     }  this.hasmany(t => t.news)     .withmany(t => t.groups)     .map(m =>         {             m.totable("groupnews");             m.mapleftkey("groupid");             m.maprightkey("newsid");         }); 

now can news based on groupid using approach. problem in insertign new news , updating.for need save newsid , groupid in groupnews table. doing . in news model defined :

    public virtual icollection<group> relatedgroups { get; set; }      public news()     {         relatedgroups = new list<group>();     } 

and same group :

    public virtual icollection<news> relatednews { get; set; }     public group()     {         relatednews = new list<news>();      } 

in news controller add :

            group group = new group();             group.relatednews.add(news); 

enter image description here

but nothing updated , newsid not adding groupnews table .

you should not define groupnews separately. meaning, should not have groupnews class defined in project. have crud operations using independent associations (a list of news in group class , list of group in news class). here's classes should like:

public class group {     ...     public group()     {          this.news = new list<news>();     }      public virtual icollection<news> news {get;set;} }  public class news {     ...     public news()     {          this.group = new list<group>();     }     public virtual icollection<group> groups {get;set;} }  public class mycontext : dbcontext {     public dbset<group> groups { get; set; }     public dbset<news> news { get; set; } } 

then can use mygroup.news.add(mynewsitem) or mynews.groups.add(mygroup). entity framework handle insertion automatically. notice should use virtual keyword if want enable lazy loading associations.


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

How can I fetch data from a web server in an android application? -

jquery - How can I dynamically add a browser tab? -