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 articleby 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.