0

我有两个模型:

public class Exchanger : BaseContract
{
    [DataMember, Key, Column(TypeName = "bigint")]
    public long Id { get; set; }

     ....
    [DataMember]
    public virtual ICollection<PaymentSystem> PaymentSystems { get; set; }

}

 [DataContract, Serializable]
 public class PaymentSystem : BaseContract
 {
    [Key, Column(TypeName = "bigint"), DataMember]
    public long Id { get; set; }

     ...

    [DataMember, JsonIgnore]
    public virtual ICollection<Exchanger> ExchangersSupport { get; set; }

}

和流利的 api 方向具有多对多的关系:

 modelBuilder.Entity<Exchanger>()
     .HasMany(t => t.PaymentSystems)
     .WithMany(t => t.ExchangersSupport)
     .Map(m => m.ToTable("ExchangerToPaymentSystem"));

插入代码:

  public void Create(Exchanger ex, long clientId)
       {
         if (_context != null)
        {
             ex.ClientId = clientId;
             ex.LastTimeUpdated = DateTime.UtcNow;
             _context.Exchangers.Add(ex);
             _context.SaveChanges();
        }

    }

当我在 Exchanger 表中插入新条目时,EF 在 ExchangerToPaymentSystem 表中创建条目时,它也会同时在 PaymentSystem 表中创建相同的条目。当我更新时,没有任何反应。我做错了什么?

4

3 回答 3

0

对于中间表,您的映射配置必须类似于以下内容:

this.ToTable("ExchangerToPaymentSystem");
            this.HasKey(e => e.Id);

            this.HasRequired(e => e.Exchanger )
                .WithMany(e => e.ExchangersSupport )
                .HasForeignKey(pc => pc.ExchangerId);


            this.HasRequired(pc => pc.PaymentSystem )
                .WithMany(p => p.PaymentSystems)
                .HasForeignKey(pc => pc.PaymentSystemId);

当您的实体来自不同的数据上下文时,通常会发生这种行为。确保所有实体都来自相同的数据上下文。

于 2012-11-15T12:51:56.777 回答
0

所以,当你这样做

var exchange = new Exchanger() { PaymentSystems = paymentSystems, ... };

它会自动为您在链接表中创建记录,这是预期的和必需的。我不完全确定我明白现在的问题是什么......

于 2012-11-15T12:58:45.450 回答
0

好的,我不知道我必须将 PaymentSystems 集合重新附加到对象上下文,它不会自动重新附加,而是标记为新的(状态 = 添加)。

 public void Create(Exchanger ex, long clientId)
    {
        if (_context != null)
        {
            ex.ClientId = clientId;
            ex.LastTimeUpdated = DateTime.UtcNow;

           **var ps = ex.PaymentSystems.Select(x=>x.Id);
            var ps2 = _context.PaymentSystems.Where(x => ps.Any(y => y == x.Id)).ToList();
            ex.PaymentSystems.Clear();
            foreach (var pp in ps2)
            {
                ex.PaymentSystems.Add(pp);
            }**

            _context.Exchangers.Add(ex);
            _context.SaveChanges();
        }

    }
于 2012-11-15T13:33:20.437 回答