MrMVC
MrMVC

Reputation: 85

Many to Many Code first Insert New Record

I have 3 tables:

When I try add new Ads, new Ads insert into Ads table and new AdsAdsCategory insert into AdsAdsCategory, but a new record insert into AdsCategory

How can I solve this problem?

public class Ads
{
        public int Id { get; set; }

        public string Name { get; set; }

        public virtual ICollection<AdsCategory> AdsCategories { get; set; }
}

public class AdsCategory
{
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Ads> Ads { get; set; }
}

I want insert data just into Ads and AdsAdsCategory (but Entity Framework will insert new duplicate row in AdsCategory)

Insert method:

public async Task<IHttpActionResult> PostAds(Ads ads)
{
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Adses.Add(ads);

            int result = await db.SaveChangesAsync();

            if (result > 0)
            {
                return Ok(result);
            }

            return InternalServerError();
}

Upvotes: 2

Views: 818

Answers (1)

scottdavidwalker
scottdavidwalker

Reputation: 1541

You should really map it to a new table using Fluent API

 public class Ads
 {
    public Ads()
    {
        AdsCategories= new HashSet<AdsCategory>();
    }
    public int AdsId { get; set; }

    public string Name { get; set; }

    public virtual ICollection<AdsCategory> AdsCategories { get; set; }
 }


 public class AdsCategory
 {
    public AdsCategory()
    {
        Ads= new HashSet<Ads>();
    }
    public int AdsCategoryId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Ads> Ads { get; set; }
 }

Then in your db context file, use the OnModelCreating to map them to a new table

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<Ads>().
            HasMany(c => c.AdsCategories).
            WithMany(p => p.Ads).
            Map(
                m =>
                {
                    m.MapLeftKey("AdsId");
                    m.MapRightKey("AdsCategoryId");
                    m.ToTable("Whateveryoucallyourtable");
                });
 }

EDIT Post

    public async Task<IHttpActionResult> PostAds(Ads ads, AdsCategory adsCategory)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        Ads.AdsCategories.Add(adsCategory);
        AdsCategory.Ads.Add(ads)

        int result = await db.SaveChangesAsync();

        if (result > 0)
        {
            return Ok(result);
        }

        return InternalServerError();
    }

Upvotes: 1

Related Questions