简体   繁体   中英

Entity Framework : many to many relationship , Insert and update

I have a news entity and I get the news based on their NewsID. then I defined a new entity , a Group and I want to get the news based on their Group ID. I tried to handle this (many to many) relationships using this article by using code first approach.

在此处输入图片说明

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 get the news based on Their GroupID using this approach. but the problem is in insertign new News and updating.For that I need to save NewsID and GroupId in GroupNews table. for doing this . in News model i defined :

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

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

and the same for 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);

在此处输入图片说明

but nothing is updated and the NewsID is not adding to my GroupNews table .

You should not define GroupNews separately. Meaning, you should not have a GroupNews class defined in your project. You have to do CRUD operations using independent associations (a list of News in Group class and a list of Group in your News class). Here's what your classes should look 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 you can use myGroup.News.Add(myNewsItem) or myNews.Groups.Add(myGroup) . Entity Framework will handle the insertion automatically. Notice you should use virtual keyword if you want to enable lazy loading for your associations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM