实体框架保存多对多关系

时间:2013-05-13 09:02:42

标签: c# entity-framework many-to-many

我有一个新闻实体,我定义了一个约束,使用GroupNews Table根据GroupID获取新闻。现在,当我添加新消息因为没有任何内容添加到GroupNews表时,新闻不会显示在网页中。我需要将NewsID和GroupID添加到GroupNews表。

enter image description here

我在mywebContect.cs中定义了GroupNews:

public class Groupnews : DbContext
{
    public DbSet<Group> Group { get; set; }
    public DbSet<News> News { get; set; }

    public Groupnews()
        : base("MyDb")
    {
    }
}
   modelBuilder.Entity<Group>().
     HasMany(c => c.RelatedNews).
     WithMany(p => p.RelatedGroups).
     Map(
      m =>
      {
          m.ToTable("GroupNews");
          m.MapLeftKey("GroupID");
          m.MapRightKey("NewsID");
      });

也在我定义的新闻实体中:

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

和新闻一样。用于将GroupID和NewsID保存到GroupNews表中我在EventController中向CreateEvent方法添加了两行:

        MeetingBoard.DAL.MeetingBoardContext.GroupNews.EventID = happening.EventID;
        Group p = new Group();
        MeetingBoard.DAL.MeetingBoardContext.GroupNews.GroupID = p.GroupID;

这里是CreateEvent方法:

public void CreateEvent(string json_data)
{
    Event happening = Event.FromJson(json_data);

    if (happening.EventID == 0)
    {
        happening.CreatorID = UserHelper.GetCurrentUser().UserID;

        eventService.CreateEvent(happening);

        projectTag_service.AddProjectTag(happening);

        broadcastContext.Clients.triggerChange("event");
    }
    else
    {
        Event saved_happening = eventService.GetEvent(happening.EventID);

        saved_happening.Title = happening.Title;
        saved_happening.Description = happening.Description;
        saved_happening.Location = happening.Location;
        saved_happening.StartDate = happening.StartDate;
        saved_happening.EndDate = happening.EndDate;
        eventService.SaveEvent();

        projectTag_service.RemovesProjectTagsByEventID(happening.EventID);
        projectTag_service.AddProjectTag(happening);
        MeetingBoard.DAL.MeetingBoardContext.Groupevents.EventID = happening.EventID;
        Group p = new Group();
        MeetingBoard.DAL.MeetingBoardContext.Groupevents.GroupID = p.GroupID;
        broadcastContext.Clients.triggerChange("event_force");
    }
}

但GroupNews表仍未更新,我无法在页面中看到添加的新闻。

0 个答案:

没有答案