PRASAD GODBOLE

PRASAD GODBOLE

  • NA
  • 12
  • 6.7k

Remove records from junction table in ASP.NET MVC

Mar 5 2018 7:40 AM
Hello,
 
I am developing 1 sample application which will add the news and sources related to it using Code First approach. So one news has multiple sources and one source has multiple news i.e. its many to many relationship. I have created the "news"  and "source" model. For creating junction table I am not using model instead it is created using Fluent API. Below is code for that.
 
public class News
{
[Key]
public int NewsId { get; set; }
public string NewsTitle { get; set; }
public string NewsContent { get; set; }
public int CategoryId { get; set; }
public Category category { get; set; }
public ICollection sources { get; set; }
}
 
public class Source
{
[Key]
public int SourceId { get; set; }
public string SourceName { get; set; }
public ICollection news { get; set; }
}
 
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//base.OnModelCreating(modelBuilder);
//modelBuilder.Entity().HasKey(sn => new { sn.SourceId, sn.NewsId });
modelBuilder.Entity()
.HasMany(n => n.news)
.WithMany(s => s.sources)
.Map(ns =>
{
ns.MapLeftKey("SourceId");
ns.MapRightKey("NewsId");
ns.ToTable("SourceNews");
});
}
 
Now while editing the particular news I want to remove all records of that particular news and then add newone to junction table. Can any one please help in this and how to do it wihout junction table model?
 
Thanks 
Prasad