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

StackOverflow https://stackoverflow.com/questions/20652416

  •  19-09-2022
  •  | 
  •  

Question

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();
                    }
Was it helpful?

Solution

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; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top