Entity Framework - how to save entity without saving related objects - entity-framework

In my Entity Framework, I have three related entities 'Client', 'ClientAddress' and 'LookupAddressType'. "LookupAddressType" is a master class specifying the type of available address type, like business address, residential address etc. ClientAddress depend on LookupAddresstype and Client. While saving a Client entity with relevant ClientAddress data, i'm getting following error.
"Violation of PRIMARY KEY constraint 'PK_LookupAddressType'. Cannot
insert duplicate key in object 'dbo.LookupAddressType'. The statement
has been terminated.
I do not need LookupAddressType to be inserted. Here I just need the relevant lookupAddressTypeId to be inserted in clientAddress entity.
The Saving code is like this:
Add(Client);
_objectContext.SaveChanges();
how can i do this?
The Load Code is below:
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);
}

Well I did this to the following lines of code to make it work.
if (rcboClientAddType.SelectedIndex != -1)
{
clientAddress.LookupAddressType = new EFEntities.LookupAddressType
{
AddressTypeID = (Guid) (rcboClientAddType.SelectedValue),
AddressTypeDescription = rcboClientAddType.Text
};
//clientAddress.AddressType.Id = Convert.ToByte(rcboClientAddType.SelectedValue);
}
I changed the above code into this
if (rcboClientAddType.SelectedIndex != -1)
{
//clientAddress.LookupAddressType = new EFEntities.LookupAddressType
// {
// AddressTypeID = (Guid) (rcboClientAddType.SelectedValue),
// AddressTypeDescription = rcboClientAddType.Text
// };
clientAddress.AddressTypeID = (Guid)(rcboClientAddType.SelectedValue);
}

Related

I am getting multiple headers and footers in word document, getting null in policy.GetFirstPageHeader() using NPOI

I am getting multiple headers and footers in a Word document; I cannot differentiate the firstpage, default(odd), or even headers.
When I am trying to call policy.GetFirstPageHeader() I am getting a null value.
XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document);
var headerList = document.HeaderList;
var footerList = document.FooterList;
var firstPageHeader = policy.GetFirstPageHeader();
var firstPageFooter = policy.GetFirstPageFooter();
XWPFHeader header = policy.GetDefaultHeader();
XWPFHeader even = policy.GetEvenPageHeader();
XWPFHeader odd = policy.GetOddPageHeader();
I am getting null values. Can any one suggest how to differentiate headers in a Word document?
var listOfheaders = new List<CT_HdrFtrRef>();
foreach (var par in document.Paragraphs)
{
var ParagraphsectPr = (CT_P)par.GetType().GetField("paragraph", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(par);
if (ParagraphsectPr.pPr.sectPr != null)
{
foreach (var headerref in ParagraphsectPr.pPr.sectPr.headerReference)
{
listOfheaders.Add(headerref);
}
}
}
foreach (var list in listOfheaders)
{
var relatedPart = document.GetRelationById(list.id);
XWPFHeader hdr = null;
if (relatedPart != null && relatedPart is XWPFHeader)
{
hdr = (XWPFHeader)relatedPart;
}
// Assign it
ST_HdrFtr type = list.type;
if (!string.IsNullOrEmpty(hdr.Text))
{
if (type == ST_HdrFtr.first)
{
firstPageHeadr = hdr;
}
else if (type == ST_HdrFtr.even)
{
evenPageHeader = hdr;
}
else
{
defaultHeader = hdr;
}
}
}

IPP Create Customers Never Appears in QBD

I am trying to add a customer and an invoice to QuickBooks, but neither appear. QuickBooks responds with this XML:
http://pastebin.com/PLsFbA6N
My code for adding customers and invoices appears to work and I see no errors:
public Customer BuildCustomerAddRq(JMAOrder _Order)
{
// Construct subordinate required records
//BuildStandardTermsAddRq("Web Order");
// build the main customer record
Customer QBCustomerAdd = new Customer();
var Customer = _Order.BillingAddress;
var Billing = _Order.BillingAddress;
PhysicalAddress phy = new PhysicalAddress();
// if the setting is that all orders go under the same customer ID, then push
// the address lines down one and store the customer name on address line 1.
if (_qboSettings.CustomerID == "SingleName")
{
QBCustomerAdd.DBAName = "Web Store";
QBCustomerAdd.Email = new EmailAddress[] { new EmailAddress() { Address = "info#webstore.com", Tag = new string[] { "Business" } } };
QBCustomerAdd.GivenName = "Web";
QBCustomerAdd.Active = true;
QBCustomerAdd.FamilyName = "Store";
phy.Line1 = "Web Store";
phy.Line2 = "";
phy.Tag = new string[] { "Billing" };
}
else
{
//QBCustomerAdd.DBAName = GetCustId(_Order);
QBCustomerAdd.Email = new EmailAddress[] { new EmailAddress() { Address = Customer.Email, Tag = new string[] { "Business" } } };
QBCustomerAdd.GivenName = Customer.FirstName;
QBCustomerAdd.Active = true;
QBCustomerAdd.FamilyName = Customer.LastName;
if (!String.IsNullOrEmpty(Customer.PhoneNumber))
{
QBCustomerAdd.Phone = new TelephoneNumber[] { new TelephoneNumber() { FreeFormNumber = Customer.PhoneNumber, Tag = new string[] { "Business" } } };
}
phy.Line1 = Billing.Address1;
if (!String.IsNullOrEmpty(Billing.Address2))
{
phy.Line2 = Billing.Address2;
}
phy.City = Billing.City;
if (Billing.RegionName != null)
{
phy.CountrySubDivisionCode = Billing.RegionName;
}
phy.PostalCode = Billing.PostalCode;
phy.Country = Billing.CountryName;
phy.Tag = new string[] { "Billing" };
}
// build add request and exit
QBCustomerAdd.Address = new PhysicalAddress[] { phy };
try
{
Customer cu = dataServices.Add(QBCustomerAdd);
return cu;
}
catch (Exception ex)
{
ErrorMessageDataSource.Insert(new ErrorMessage(MessageSeverity.Error, "QBO", String.Format("Error adding customer : {0}", ex.ToString())));
Customer ct = new Customer();
return ct;
}
When I run Intuit Sync Manager, I see no new customer or invoice. Is it possible to add new customers to QuickBooks?
It appears that the customer entered QuickBooks in error state. I needed to add the QBCustomerAdd.Name field.
CustomerQuery cq = new CustomerQuery();
cq.ErroredObjectsOnly = true;
var bList = cq.ExecuteQuery<Customer>(dataServices.ServiceContext);

Entity Framework code first - update function failed

Inner exception message: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
dynamic obj = "";
if (model.LoadResultCount!=0)
{
obj = new LoadManagementResultsCountUserSetting();
obj.ResultsCount = Convert.ToInt16(model.LoadResultCount);
obj.Id = Convert.ToInt16(model.LoadResultCountId);
//var loadManagementResultCount = ApplicationService.GetSettings<LoadManagementResultsCountUserSetting>(f => f.Id == model.LoadResultCountId).FirstOrDefault();
//ApplicationService.Remove(loadManagementResultCount);
SaveResultCountUserSettings(obj, model);
}
if (model.PlanningResultCount!=0)
{
obj = new PlanningManagementResultsCountUserSetting();
obj.ResultsCount = Convert.ToInt16(model.PlanningResultCount);
obj.Id = Convert.ToInt16(model.PlanningResultCountId);
//var planningManagementResultCount = ApplicationService.GetSettings<PlanningManagementResultsCountUserSetting>().Where(f => f.Id == model.PlanningResultCountId).FirstOrDefault();
//ApplicationService.Remove(planningManagementResultCount);
SaveResultCountUserSettings(obj, model);
}
private void SaveResultCountUserSettings(dynamic obj, ResultCountViewModel model)
{
obj.IsEnabled = true;
obj.IsPrimary = model.IsPrimary;
obj.StartDate = DateTime.UtcNow;
obj.ModifiedDate = DateTime.UtcNow;
obj.ModifiedBy = AuthenticatedUser;
ApplicationService.Save(obj);
}
public void Save(BaseLogixSetting setting)
{
if (setting != null)
{
if (setting.Id > 0)
SettingsRepository.Attach(setting);
else
SettingsRepository.Add(setting);
Commit();
}
}

Entity Framework overwrites data when 2 two people save data simultaneously

In a function I pass a list of related values and loop over them to save changes in the database. All works well until 2 or more people use the same page to update different entities .Then only that data gets saved for which the changes were made more recently.
public bool UpdatePermanentDifferenceBL(List<PermanentDifferenceProperties> permDiffDetails)
{
try
{
int permanentDifferenceID=0;
int taxEntityID = 0;
int mapid = 0;
//using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
//{
Topaz.DAL.PermanentDifference permDiff;
for (int i = 0; i < permDiffDetails.Count; i++)
{
if ((bool)(HttpContext.Current.Session[GlobalConstant.currentDataSet]) == true && (int)(HttpContext.Current.Session[GlobalConstant.snapShotID]) == 0)
{
using (var ctx = new TopazDbContainer())
{
try
{
permanentDifferenceID = permDiffDetails[i].PermanentDifferenceID;
taxEntityID = permDiffDetails[i].TaxEntityID;
mapid = permDiffDetails[i].MapID;
permDiff = new Topaz.DAL.PermanentDifference();
permDiff = ctx.PermanentDifference.Where(p => p.PermanentDifferenceID == permanentDifferenceID && p.TaxEntityID == taxEntityID && p.MapID == mapid).SingleOrDefault();
permDiff.Business = permDiffDetails[i].Business;
permDiff.Interest = permDiffDetails[i].Interest;
permDiff.Corporate = permDiffDetails[i].Corporate;
permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
permDiff.Total = permDiffDetails[i].Total;
permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
permDiff.ModifiedDate = DateTime.Now;
ctx.SaveChanges();
}
catch (System.Data.OptimisticConcurrencyException ex)
{
permanentDifferenceID = permDiffDetails[i].PermanentDifferenceID;
taxEntityID = permDiffDetails[i].TaxEntityID;
mapid = permDiffDetails[i].MapID;
permDiff = new Topaz.DAL.PermanentDifference();
ctx.Refresh(System.Data.Objects.RefreshMode.StoreWins, permDiff);
permDiff = ctx.PermanentDifference.Where(p => p.PermanentDifferenceID == permanentDifferenceID && p.TaxEntityID == taxEntityID && p.MapID == mapid).SingleOrDefault();
permDiff.Business = permDiffDetails[i].Business;
permDiff.Interest = permDiffDetails[i].Interest;
permDiff.Corporate = permDiffDetails[i].Corporate;
permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
permDiff.Total = permDiffDetails[i].Total;
permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
permDiff.ModifiedDate = DateTime.Now;
ctx.SaveChanges();
}
}
}
//ctx.ContextOptions.UseLegacyPreserveChangesBehavior = true;
}
//}
//using (UnitOfWork uow = new UnitOfWork())
//{
// for (int i = 0; i < permDiffDetails.Count; i++)
// {
// if ((bool)(HttpContext.Current.Session[GlobalConstant.currentDataSet]) == true && (int)(HttpContext.Current.Session[GlobalConstant.snapShotID]) == 0)
// {
// Repository.PermanentDifferenceRepository pDiffRepo = new Repository.PermanentDifferenceRepository(uow);
// Topaz.DAL.PermanentDifference permDiff = pDiffRepo.GetByEntityId(permDiffDetails[i].PermanentDifferenceID, permDiffDetails[i].TaxEntityID, permDiffDetails[i].MapID);
// permDiff.Business = permDiffDetails[i].Business;
// permDiff.Interest = permDiffDetails[i].Interest;
// permDiff.Corporate = permDiffDetails[i].Corporate;
// permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
// permDiff.Total = permDiffDetails[i].Total;
// permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
// permDiff.ModifiedDate = DateTime.Now;
// pDiffRepo.ApplyChanges(permDiff);
// }
// else
// {
// int snapshotID = (int)(HttpContext.Current.Session[GlobalConstant.snapShotID]);
// SnapShotPermanentDifferenceRepository pDiffRepo = new SnapShotPermanentDifferenceRepository(uow);
// SnapShotPermanentDifference permDiff = pDiffRepo.GetByEntityId(permDiffDetails[i].PermanentDifferenceID, permDiffDetails[i].TaxEntityID, permDiffDetails[i].MapID,snapshotID);
// permDiff.SnapshotID = snapshotID;
// permDiff.Business = permDiffDetails[i].Business;
// permDiff.Interest = permDiffDetails[i].Interest;
// permDiff.Corporate = permDiffDetails[i].Corporate;
// permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
// permDiff.Total = permDiffDetails[i].Total;
// permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
// permDiff.ModifiedDate = DateTime.Now;
// pDiffRepo.ApplyChanges(permDiff);
// }
// }
// uow.SaveChanges();
return true;
}
catch (Exception ex)
{
TopazErrorLogs.AddTopazErrorLogBL(ex, 1, 1);
throw new TopazCustomException(GlobalConstant.errorMessage);
}
}
Any urgent assistance is much appreciated.
The common way to solve this is adding additional column to every table where you want to handle concurrency. This column will have ROWVERSION or TIMESTAMP data type. Once you map tables in EDMX you will get a new computed property of type byte[] and set its Concurrency mode to fixed. This setting will force EF to add additional WHERE condition to every UPDATE or DELETE statement validating that row version is the same as it was when the record was loaded from the database. If the row version is not the same (another thread updated the record) the record from modification is not found and you will get exception.
Database will change the value every time you update the record automatically. You just need to ensure that your entity uses the value which was retrieved when the entity was loaded from the database.
Apologies all the viewstate and to some extent session was the culprit and not EntityFramework.

Entity Framework 4.0 Error The object could not be added or attached EntityReference has EntityKey value that does not match EntityKey

Hi everybody im starting to work with Entity Framework 4.0 and ASP.NET 4.0 i'm trying to make a master detail web page and i'm having problems when i try to add new items to a previously recorded items below is the i made for this:
private void guardarOrdenMedicamento()
{
InventarioSIAIplusEntities SIAplusContext = (InventarioSIAIplusEntities)(Session["context"]);
InvOrden orden;
string resultMessage;
if (DetalleMedicamentosOrden.Count == 0)
{
MessageBox1.ShowError("Debe especificar al menos un medicamento para la orden.");
return;
}
if (txtIDorden.Text.Trim() == "")
{
orden = new InvOrden();
orden.IDcentro = Convert.ToInt32(ddlCentros.SelectedValue);
orden.estado = ddlEstadoOrden.SelectedValue;
orden.fecha = Convert.ToDateTime(txtFechaCreacion.Text);
orden.comentario = txtComentarioOrden.Text;
orden.usuarioCrea = "Jeanc";
SIAplusContext.AddToInvOrdenes(orden);
resultMessage = "La orden fue registrada satisfactoriamente";
}
else
{
int idorden = Convert.ToInt32(txtIDorden.Text.Trim());
orden = SIAplusContext.InvOrdenes.Where(c => c.IDorden == idorden).First();
orden.estado = ddlEstadoOrden.SelectedValue;
orden.fecha = Convert.ToDateTime(txtFechaCreacion.Text);
orden.comentario = txtComentarioOrden.Text;
orden.usuarioCrea = "Jeanc";
resultMessage = "La orden fue actualizada satisfactoriamente";
foreach (var item in DetalleMedicamentosOrden)
{
if (item.IDorden == 0)
{
// item.IDorden = idorden;
// item.InvOrdenReference.EntityKey = orden.EntityKey;
//neww System.Data.EntityKey("InventarioSIAIplusEntities.InvOrdenes", "IDorden", orden.IDorden);
// SIAplusContext.AddToInvOrdenDets(item);
item.InvOrden = orden;
//
// SIAplusContext.AddToInvOrdenDets(item);
//orden.InvOrdenDets.Add(item);
}
else
{
InvOrdenDet det = SIAplusContext.InvOrdenDets.Where(c => c.IDorden == item.IDorden && c.IDmedicamento == item.IDmedicamento).First();
det.cantidadApr = item.cantidadApr;
det.cantidadSol = item.cantidadSol;
det.comentario = item.comentario;
}
}
}
SIAplusContext.SaveChanges();
}
The Error is :The object could not be added or attached because its EntityReference has an EntityKey property value that does not match the EntityKey for this object.
Thanks For any help with this.
I think that the problem is here:
item.InvOrden = orden;
You either have to use AddObject or update the values of an existing object.