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

  • Home
  • SEARCH
  • 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 6576633
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T15:32:11+00:00 2026-05-25T15:32:11+00:00

Here is a business logic I need to implement: There are multiple entity types

  • 0

Here is a business logic I need to implement:

There are multiple entity types in data model, e.g.: User, UserProfile, UserProfileValue, UserExtendedData etc.

When creating some entities like User, I need auto create other entities logically linked (usually with 1:1 relationship in db) for example UserProfile.

Each entity has a controller with OnCreating/OnCreated, OnUpdating/OnUpdated methods, which are invoked from overridden SaveChanges methods of my datacontext class.

public override int SaveChanges(SaveOptions options)
{
    IEnumerable<ObjectStateEntry> addedEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Added);
    IEnumerable<ObjectStateEntry> changedEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
    IEnumerable<ObjectStateEntry> deletedEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Deleted);

    InvokeSavingControllers(addedEntities, changedEntities, deletedEntities);

    //some other code

    int rowsAffected = base.SaveChanges(options);

    InvokeSavedControllers(addedEntities, changedEntities, deletedEntities);

    return rowsAffected;
}

if I implemented auto creation in my User.OnCreating() method then eventually no OnCreating() controllers will be invoked for all auto created children entities since the collection addedEntities is not updated with new entries.

One of my ideas is to perform auto creation of the dependent entities by handling ObjectStateManagerChanged of data context

private void ObjectStateManagerObjectStateManagerChanged(object sender, System.ComponentModel.CollectionChangeEventArgs e)
{
    if (e.Action == CollectionChangeAction.Add)
    {
        var state = ObjectStateManager.GetObjectStateEntry(e.Element).State;
        if (state == EntityState.Added)
        {
            //should call on creating handlers
            if (e.Element is User)
            {
                User user = (User)e.Element;
                user.UserProfile = UserProfile.CreateDefaultProfile();
            }
        }
    }
}

But unfortunately I am getting NullReferrence exception if I do it this way. Even if I try to modify the property of user within ObjectStateManagerObjectStateManagerChanged I get exception.

Any thoughts or suggestions on how to implement the required functionality?

EDIT:

Null Reference I am getting:

System.NullReferenceException was unhandled by user code
  Message=Object reference not set to an instance of an object.
  Source=System.Data.Entity
  StackTrace:
       at System.Data.Objects.ObjectContext.AddSingleObject(EntitySet entitySet, IEntityWrapper wrappedEntity, String argumentName)
       at System.Data.Objects.ObjectContext.AddObject(String entitySetName, Object entity)
       at Edm.Entity.Entities.AddObject(Object entity) 

And Edm.Entity.Entities.AddObject(Object entity) is where new User object is added to the context.

EDIT2:
Not sure what I’ve changed but the same code as above started to throw the following exception:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
  <code></code>
  <message xml:lang="en-US">An error occurred while processing this request.</message>
  <innererror>
    <message>Object reference not set to an instance of an object.</message>
    <type>System.NullReferenceException</type>
    <stacktrace>   at System.Data.Objects.DataClasses.EntityReference`1.Exclude()&#xD;
   at System.Data.Objects.DataClasses.RelationshipManager.RemoveRelatedEntitiesFromObjectStateManager(IEntityWrapper wrappedEntity)&#xD;
   at System.Data.Objects.ObjectContext.AddObject(String entitySetName, Object entity)&#xD;
   at System.Data.Services.Providers.ObjectContextServiceProvider.CreateResource(String containerName, String fullTypeName)&#xD;
   at System.Data.Services.UpdatableWrapper.CreateResource(String containerName, String fullTypeName)&#xD;
   at System.Data.Services.Serializers.SyndicationDeserializer.CreateObject(SegmentInfo segmentInfo, Boolean topLevel, SyndicationItem item)&#xD;
   at System.Data.Services.Serializers.SyndicationDeserializer.CreateSingleObject(SegmentInfo segmentInfo)&#xD;
   at System.Data.Services.Serializers.Deserializer.ReadEntity(RequestDescription requestDescription)&#xD;
   at System.Data.Services.Serializers.Deserializer.HandlePostRequest(RequestDescription requestDescription)&#xD;
   at System.Data.Services.DataService`1.HandlePostOperation(RequestDescription description, IDataService dataService)&#xD;
   at System.Data.Services.DataService`1.ProcessIncomingRequest(RequestDescription description, IDataService dataService)&#xD;
   at System.Data.Services.DataService`1.BatchDataService.HandleBatchContent(Stream responseStream)</stacktrace>
  </innererror>
</error>
  • 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-05-25T15:32:12+00:00Added an answer on May 25, 2026 at 3:32 pm

    I have exactly the same issue. It seems to be a problem to add another EntityObject during the ObjectStateManagerChanged event. The strange thing is that my code (and your code probably too) is working fine in .net 3.5, but gives a NullReferenceException in 4.0.

    I’ve debugged the .net framework, and figured out that it crashes in the internal ObjectContext.AddSingleObject method after it invokes the ObjectStateManagerChanged event. This exception occures because the internal ProcessedEntities hashset is made null at the end of the public AddObject method. But if the EntityObject is created during the ObjectStateManagerChanged event this hashset should not be made null.

    This seems to be a .net framework 4.0 bug.

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

Sidebar

Related Questions

Here's the scenario: ASP.NET MVC2 Web Application Entity Framework 4 (Pure POCO's, Custom Data
I've recently asked a question regarding best ways of separating business logic from data
Say you have an application divided into 3-tiers: GUI, business logic, and data access.
We're developing a middle-tier to replace an existing business logic/data access layer. One of
I'm using Entity Framework for the first time, and I need to add business
I am in a Model1 (Model1)and I need to run some business logic that
I need a gear for custom authorization in business logic classes. It has to
Here's my problem at a high level: We have two business applications. App1 inputs
Here's the deal: I'm in the process of planning a mid-sized business application that
At work here, we have a box serving XML feeds to business partners. Requests

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.