【问题标题】:Entity Framework 5. Update many to many relationship gives violation of primary key实体框架 5. 更新多对多关系会违反主键
【发布时间】:2013-01-29 10:55:09
【问题描述】:

我见过很多这样的问题,但是那些人正在调用 .Add 方法来处理我不是的多对多关系。我正在使用 WebApi

我是否想调用 .Clear() 然后在实体框架 5 中重新添加更新的实体,或者它应该是自动的,我做错了什么?

我正在使用工作单元和通用实体框架存储库模式。

这是相关代码:

 public HttpResponseMessage Put(PromDto promDto)
{
    var creditCardsIds = string.IsNullOrEmpty(promDto.CreditCards) ? null : promDto.CreditCards.Split(',').Select(int.Parse);
    var branchesIds = string.IsNullOrEmpty(promDto.Branches) ? null : promDto.Branches.Split(',').Select(int.Parse);

    var promotion = Uow.Promotions.GetById(promDto.Id);

    promotion.CreditCards = creditCardsIds != null ? Uow.CreditCards.GetByPredicate(t => creditCardsIds.Contains(t.Id)).ToList() : null;
    promotion.Branches = branchesIds != null ? Uow.Branches.GetByPredicate(t => branchesIds.Contains(t.Id)).ToList() : null;

    if (ModelState.IsValid)
    {
        Uow.Promotions.Update(promotion);
        Uow.Commit();
        return new HttpResponseMessage(HttpStatusCode.NoContent);
    }

    throw new HttpResponseException(HttpStatusCode.BadRequest);
}

上下文

modelBuilder.Entity<Branch>().
    HasMany(p => p.Promotions).
    WithMany(s => s.Branches).
    Map(
    m =>
    {
      m.MapLeftKey("BranchId");
      m.MapRightKey("PromotionId");
      m.ToTable("Branch_Promotion");
    });

modelBuilder.Entity<Promotion>().
    HasMany(tt => tt.CreditCards).
    WithMany(p => p.Promotions).
    Map(
    m =>
    {
     m.MapLeftKey("PromotionId");
     m.MapRightKey("CreditCardId");
     m.ToTable("Promotion_CreditCard");
    });

我应该这样称呼它吗?

promocion.CreditCards.Clear();
promocion.Branches.Clear();

提前致谢。吉列尔莫。

【问题讨论】:

    标签: entity-framework entity-framework-4 entity-framework-5


    【解决方案1】:

    添加这个解决了它:

    var promotion = Uow.Promotions.GetByPredicateIncluding(p => p.Id == promotionDto.Id, a => a.CreditCards, a => a.Branches).ToList().FirstOrDefault();
    

    加载相关的实体。

    似乎需要加载它们以便 Entity Framework 知道它们是否是新的。

    如果有人有更好的解释,请随时添加任何评论。

    最好的问候。吉列尔莫。

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 2014-10-01
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      相关资源
      最近更新 更多