简体   繁体   中英

Entity Framework is trying to save the Foreign key tables along with the entity save. How to prevent that?

When i am saving belwo CounterpartyFrequency entity as below, its trying to add the legalEntity attached to it. How can i prevent that. i just need the counterpartyfrequency table to insert with CounterpartyFrequencyId and LegalEntityId . Plz share your thoughts

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

The Entity i want to save is above

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

You need to make the LegalEntity as virtual:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM