0
在我的實體框架,我有三個相關實體「客戶」,「ClientAddress」和「LookupAddressType」。 「LookupAddressType」是一個主類指定可用地址類型的類型,如商務地址,居住地址等ClientAddress取決於LookupAddresstype和客戶。雖然正在保存 a 客戶端實體與相關的ClientAddress數據,我得到以下錯誤。實體框架 - 如何拯救實體,不保存相關對象
「PRIMARY KEY約束 'PK_LookupAddressType' 的相關規定。不能 插入重複鍵對象dbo.LookupAddressType「。聲明 已終止。
我不需要LookupAddressType被插入在這裏我只需要相關lookupAddressTypeId在clientAddress實體插入
保存代碼是這樣的:
Add(Client);
_objectContext.SaveChanges();
我該怎麼做?
負載代碼如下:
private void LoadClientDetails(EFEntities.Client _Client)
{
EFEntities.LookupClientStatu clientStatus;
var clientAddressList = new List<ClientAddress>();
if (_Client == null)
{
return;
}
//Assign data to client object
_Client.ClientName = rtxtName.Text;
_Client.Alias = rtxtAlias.Text;
_Client.ClientCode =Int32.Parse(rtxtClientCode.Text);
_Client.TaxPayerID = rtxtTaxPayerId.Text;
if (rcboStatus.SelectedIndex != 0)
{
clientStatus = new EFEntities.LookupClientStatu
{
ClientStatusID = (Guid) (rcboStatus.SelectedValue),
ClientStatusDescription = rcboStatus.Text
};
_Client.LookupClientStatu = clientStatus;
}
//_Client.Modified = EnvironmentClass.ModifiedUserInstance.Id;
_Client.EffectiveDate = rdtEffectiveDate.Value;
if (rdtExpDate.Value != rdtExpDate.MinDate)
{
_Client.ExpirationDate = rdtExpDate.Value;
}
else
{
_Client.ExpirationDate = null;
}
_Client.StartDate = DateTime.Now;
EFEntities.ClientAddress clientAddress = null;
// Iesi.Collections.Generic.ISet<ClientAddress> clientAddress = new HashedSet<ClientAddress>();
foreach (var cAddress in _clientController.client.ClientAddresses)
{
clientAddress = cAddress;
break;
}
if (clientAddress == null)
{
clientAddress = new EFEntities.ClientAddress();
}
clientAddress.Address1 = rtxtClientAdd1.Text;
clientAddress.Address2 = rtxtClientAdd2.Text;
clientAddress.Address3 = rtxtClientAdd3.Text;
// Address type details
if (rcboClientAddType.SelectedIndex != -1)
{
clientAddress.LookupAddressType = new EFEntities.LookupAddressType
{
AddressTypeID = (Guid) (rcboClientAddType.SelectedValue),
AddressTypeDescription = rcboClientAddType.Text
};
//clientAddress.AddressType.Id = Convert.ToByte(rcboClientAddType.SelectedValue);
}
clientAddress.City = rtxtClientCity.Text;
clientAddress.Client = _Client;
\
_Client.ClientAddresses.Add(clientAddress);
}
請告訴我們,你創建新的客戶端的代碼。 – magritte 2012-07-12 08:53:22
相關對象從哪裏來?如果他們來自數據庫,EF不應該保存它們。如果您將它們添加到客戶端但您知道密鑰,則可以嘗試使用附加(.Attach)來讓EF知道具有給定密鑰的實體在數據庫中。 – Pawel 2012-07-12 08:54:32