Entity Framework: many-to-many relationship, insert and update

I have a news item and I receive news based on their NewsID. then I defined a new object, a group, and I want to receive news based on their group ID. I tried to deal with these (many, many) relationships using this article using the first code approach.

enter image description here

so in my context, I 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 I can receive news based on their GroupID using this approach. but the problem is inserting new news and updates. To do this, I need to save NewsID and GroupId in the GroupNews table. for this. in the news model that I defined:

    public virtual ICollection<Group> RelatedGroups { get; set; }

    public News()
    {
        RelatedGroups = new List<Group>();
    }

and the same for the group:

    public virtual ICollection<News> RelatedNews { get; set; }
    public Group()
    {
        RelatedNews = new List<News>();
     }

In my news controller, I add:

            Group group = new Group();
            group.RelatedNews.Add(news);

enter image description here

but nothing is updated, and NewsID does not add GroupNews to my table.

+1
1

GroupNews . , GroupNews, . CRUD ( News Group Group News). :

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; }
}

myGroup.News.Add(myNewsItem) myNews.Groups.Add(myGroup). Entity Framework . , virtual, .

+10

All Articles