Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7713927
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T01:59:39+00:00 2026-06-01T01:59:39+00:00

I have a pretty deep object hierarchy in my application, and I am having

  • 0

I have a pretty deep object hierarchy in my application, and I am having trouble saving the entities. Depending on the order I do things, I either one of two errors:

[OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.]

or

[DbUpdateException: An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.]

Here is the classes I am working with:

public class SpecialEquipment : Entity
{
    public Equipment Equipment { get; set; }
    public virtual ICollection<AutoclaveValidation> Validations { get; set; }
}

public class Equipment : Entity
{
    public string Model { get; set; }
    public string SerialNumber { get; set; }
    public Location Location { get; set; }
    public EquipmentType EquipmentType { get; set; }
    public ICollection<Identifier> Identifiers { get; set; }
}

public class Identifier : Entity
{
    public IdentifierType Type { get; set; }
    public string Value { get; set; }
}

public class Location : Entity
{
    public Building Building { get; set; }
    public string Room { get; set; }
}

What I was trying to do was populate one SpecialEquipment object based on form inputs and already existing objects in the database and then save the special equipment to push all changes through, it looks like this:

Building building = buildingService.GetExistingOrNew(viewModel.BuildingCode)); //checks to see if building exists already, if not, create it, save it, and re-query
Location location = locationService.GetExistingOrNew(viewModel.Room, building); //checks to see if location exists already, if not, create it, save it, and re-query
EquipmentType equipmentType = equipmentTypeService.GetOne(x => x.Name == EquipmentTypeConstants.Names.Special);
Equipment equipment = new Equipment{ EquipmentType = equipmentType, Location = location };
equipment.Identifiers = new Collection<Identifier>();

foreach (FormIdentifier formIdentifier in identifiers)
{
    FormIdentifier fIdentifier = formIdentifier;
    IdentifierType identifierType = identifierTypeService.GetOne(x => x.Id == fIdentifier.Key);

     equipment.Identifiers.Add(new Identifier { Type = identifierType, Value = fIdentifier.Value });

}

EntityServiceFactory.GetService<EquipmentService>().Save(equipment);
SpecialEquipment specialEquipment = new SpecialEquipment();
specialEquipment.Equipment = equipment;

specialEquipmentService.Save(specialEquipment);

This code returns Store update, insert, or delete statement affected an unexpected number of rows (0). If I comment out the foreach identifiers OR put the foreach identifiers after the equipment save and then call equipment save after the loop the code works. If I comment out the foreach identifiers and the save equipment line, I get : The INSERT statement conflicted with the FOREIGN KEY constraint "SpeicalEquipment_Equipment". The conflict occurred in database "xxx", table "dbo.Equipments", column 'Id'.

So how can I make these errors not occur but still save my object? Is there a better way to do this? Also I don’t like saving my equipment object, then associating/saving my identifiers and/or then my special equipment object because if there is an error occurring between those steps I will have orphaned data. Can someone help?

I should mention a few things that aren’t inheritly clear from code, but were some answers I saw for similar questions:

  • My framework stores the context in the HttpContext, so all the service methods I am using in my API are using the same context in this block of code. So all objects are coming from/being stored in one context.
  • My Entity constructor populates ID anytime a new object is created, no entities have a blank primary key.

Edit: At the request of comments:

My .Save method calls Insert or Update depending on if the entity exists or not (in this example insert is called since the specialEquipment is new):

 public void Insert(TClass entity)
    {
        if (Context.Entry(entity).State == EntityState.Detached)
        {
            Context.Set<TClass>().Attach(entity);
        }
        Context.Set<TClass>().Add(entity);
        Context.SaveChanges();
    }

    public void Update(TClass entity)
    {
        DbEntityEntry<TClass> oldEntry = Context.Entry(entity);

        if (oldEntry.State == EntityState.Detached)
        {
            Context.Set<TClass>().Attach(oldEntry.Entity);
        }

        oldEntry.CurrentValues.SetValues(entity);
        //oldEntry.State = EntityState.Modified;

        Context.SaveChanges();
    }

GetExistingOrNew for Building and location both are identical in logic:

 public Location GetExistingOrNew(string room, Building building)
    {
        Location location = GetOne(x => x.Building.Code == building.Code && x.Room == room);
        if(location == null)
        {
            location = new Location {Building = building, Room = room};
            Save(location);
            location = GetOne(x => x.Building.Code == building.Code && x.Room == room);
        }


        return location;
    }

Get one just passes that where predicate to the context in my repository with singleOrDefault. I am using a Service Layer/Repository Layer/Object Layer format for my framework.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T01:59:40+00:00Added an answer on June 1, 2026 at 1:59 am

    Your Insert method does not seem to be correct:

    public void Insert(TClass entity)
    {
        if (Context.Entry(entity).State == EntityState.Detached)
            Context.Set<TClass>().Attach(entity);
        Context.Set<TClass>().Add(entity);
        Context.SaveChanges();
    }
    

    specialEquipment is a new entity and the related specialEquipment.Equipment as well (you are creating both with new)

    Look what happens if you pass in the specialEquipment into the Insert method:

    • specialEquipment is detached because it is new
    • So, you attach it to the context
    • Attach attaches specialEquipment and the related specialEquipment.Equipment as well because both were detached from the context
    • Both are in state Unchanged now.
    • Now you add specialEquipment: This changes the state of specialEquipment to Added but not the state of specialEquipment.Equipment, it is still Unchanged.
    • Now you call SaveChanges: EF creates an INSERT for the added entity specialEquipment. But because specialEquipment.Equipment is in state Unchanged, it doesn’t INSERT this entity, it just sets the foreign key in specialEquipment
    • But this FK value doesn’t exist (because specialEquipment.Equipment is actually new as well)
    • Result: You get the FK constraint violation.

    You are trying to fix the problem with calling Save for the equipment but you have the same problem with the new identifiers which will finally throw an exception.

    I think your code should work if you add the specialEquipment (as the root of the object graph) at the end once to the context – without attaching it, so that the whole graph of new objects gets added, basically just:

    context.Set<SpecialEquipment>().Add(specialEquipment);
    context.SaveChanges();
    

    (BTW: Your Update also doesn’t look correct, you are just copying every property of entity to itself. The context won’t detect any change and SaveChanges won’t write any UPDATE statement to the database.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We use MixedParamHybridUrlCodingStrategy in our Wicket application in order to have pretty url parsed
I have a pretty complex object graph G with an object o1 in G
I have a rather deep hierarchy of objects that I'm trying to persist with
I have pretty much finished my first working Symbian application, but in my hastened
Is there a way to do this easily? I have a directory pretty deep
I am pretty far into my first Android application, and I have the sneaking
I have pretty good skills in PHP , Mysql and Javascript for a junior
i have pretty simple simple question (i hope so). How do i change the
I have pretty standard Qmail toaster installation. I'm using the dot files to set
I might have pretty basic question about regex. I have the following regex, which

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.