none
Cannot update an address for a company RRS feed

  • Question

  • I am using EF 4.4 I have a Company Entity that contains many address lines in the AddressLine entity.

    I am using database first and the primary fields are identity fields.

    So CompanyId is the foreign key on the AddressLine. I want to change the address for that company. So my approach - maybe not the best one - is to delete the existing address lines and add the new address lines. However I keep get errors such as "System.InvalidOperationException: The EntityKey property can only be set when the current value of the property is null." and "System.InvalidOperationException: An object with a temporary EntityKey value cannot be attached to an object context." The code is below;

    public static void UpdateAddressLinesForCompany(int companyId, IList<AddressLine> lines)
    {
       
    var company = Get(companyId);
       
    using (var db = new SherryGreenGroupEntities())
       
    {
            company
    .AddressLines.ToList().ForEach(x => db.AddressLines.DeleteObject(x));
           
    foreach (var address in lines.OrderBy(x => x.Position))
           
    {
                address
    .Created = DateTime.Now;
                address
    .CreatedBy = SessionObjects.LoggedInUser.EmployeeId;
                company
    .AddressLines.Add(address);
               
    //db.AddressLines.Attach(address);
                db
    .AddressLines.AddObject(address);
                db
    .ObjectStateManager.ChangeObjectState(address, EntityState.Modified);
           
    }

            db
    .SaveChanges();
       
    }
    }



    • Edited by arame Wednesday, February 11, 2015 11:31 AM
    Wednesday, February 11, 2015 11:08 AM

Answers

All replies

  • hi,

    does your class Addressline has the [key]? and have you set the value of the FK when you create the addressline?

     address.FKColumn = parent column???


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Wednesday, February 11, 2015 1:33 PM
  • FKColumn is CompanyId and it is set on the AddressLine parameters which are intended to be inserted.
    Wednesday, February 11, 2015 2:24 PM
  • ok noted on that..

    but why did you uncomment the "Attach"?  can you use "attach" instead of "addobject"?

    you can refer to this link.

    https://msdn.microsoft.com/en-sg/data/jj592676.aspx


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Wednesday, February 11, 2015 2:35 PM