当我在下面保存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();
}
答案 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; }
}