【问题标题】:Many to Many Code first Insert New Record多对多代码先插入新记录
【发布时间】:2017-02-12 11:50:37
【问题描述】:

我有 3 张桌子:

  • 广告
  • 广告类别
  • 广告广告类别

当我尝试添加新广告时,新广告插入到 Ads 表中,新 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 中插入数据(但 Entity Framework 会在 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();
}

【问题讨论】:

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


【解决方案1】:

你真的应该使用 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; }
 }

然后在您的数据库上下文文件中,使用 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");
                });
 }

编辑 发布

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

【讨论】:

  • ,谢谢你的回答,我试试这个方法,但我有同样的问题
  • 我可以看看你更新新表的代码吗?
  • 您正在尝试创建多对多关系,不是吗?
  • 我将广告从视图传递到控制器,控制器调用 web api,
  • 我把我的 web api 控制器用来保存广告数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-23
  • 2016-08-24
  • 2017-04-06
  • 1970-01-01
相关资源
最近更新 更多