实体框架正在尝试将外键表与实体保存一起保存。怎么预防?

时间:2013-12-18 07:50:23

标签: c# entity-framework-4.1

当我在下面保存belwo CounterpartyFrequency实体时,它试图添加附加到它的legalEntity。我怎么能阻止这一点。我只需要使用CounterpartyFrequencyId和LegalEntityId插入对方频率表。 Plz分享您的想法

[DataContract]
    public class CounterpartyFrequency : EntityBase
    {
        [DataMember]
        [Key]
        public int CounterpartyFrequencyId { get; set; }

        [DataMember]
        public string LegalEntityId { get; set; }

        [DataMember]
        [ForeignKey("LegalEntityId")]
        public LegalEntity LegalEntity { get; set; }
   }

我要保存的实体位于

之上
using (var dbContext = ConfigurationContext.CreateContext(dbConnection))
                    {
                        foreach (var counterpartyFrequency in counterpartyFrequencies)
                        {


                            if (
                                dbContext.CounterpartyFrequencies.Any(
                                    (x) => x.CounterpartyFrequencyId == counterpartyFrequency.CounterpartyFrequencyId))
                            {
                                dbContext.CounterpartyFrequencies.Attach(counterpartyFrequency);
                            }
                            else
                            {
                               dbContext.CounterpartyFrequencies.Add(counterpartyFrequency);
                            }
                        }

                       var noc =  dbContext.SaveChanges();
                    }

1 个答案:

答案 0 :(得分:2)

您需要将LegalEntity设为虚拟:

[DataContract]
public class CounterpartyFrequency : EntityBase
{
    [DataMember]
    [Key]
    public int CounterpartyFrequencyId { get; set; }

    [DataMember]
    public string LegalEntityId { get; set; }

    [ForeignKey("LegalEntityId")]
    public virtual LegalEntity LegalEntity { get; set; }
}