多对多代码首先插入新记录

时间:2017-02-12 11:50:37

标签: c# asp.net asp.net-mvc entity-framework ef-code-first

我有3张桌子:

  • 广告
  • AdsCategory
  • AdsAdsCategory

当我尝试添加新广告时,新广告会插入到广告表中,新的AdsAdsCategory会插入到AdsAdsCategory中,但会在AdsCategory中添加新记录

我该如何解决这个问题?

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; }
}

我希望将数据插入到Ads和AdsAdsCategory中(但实体框架会在AdsCategory中插入新的重复行)

插入方法:

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();
}

1 个答案:

答案 0 :(得分:0)

您应该使用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; }
 }

然后在db上下文文件中,使用OnModelCreating将它们映射到新表

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 交

    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();
    }