Entity Framework - trying to insert null values when creating a new object

I'm having the same problem that a few of you have had - when trying to insert a new object, EF inserts null values for some of their properties, and the insert fails.

First let me describe the structure of our DB. Its an event management system, in which each event needs to be associated with a practice group, stored in a cache table but ultimately fetched from Active Directory. I manually created the join table - is that a problem? Anyway, so Event has a foreign key pointing to EventPracticeGroup, which has a foreign key pointing to PracticeGroupCache. PracticeGroupCache also has a RegionId pointing to the Regions table.

The problem comes when trying to insert a new EventPracticeGroup object. Below is the code I'm currently using:

var eventPracticeGroup = new EventPracticeGroup();
if (TryUpdateModel<EventPracticeGroup>(eventPracticeGroup))
{
    /*
    var eventId = EventScheduleRepository.GetById(Convert.ToInt32(Request.QueryString["EventScheduleId"])).EventId;
    eventPracticeGroup.Event = EventRepository.GetById(eventId);
    eventPracticeGroup.PracticeGroupCache = PracticeGroupCacheRepository.GetById(eventPracticeGroup.PracticeGroupCacheId);
    eventPracticeGroup.PracticeGroupCache.Region = RegionRepository.GetById(eventPracticeGroup.PracticeGroupCache.RegionId);
    EventPracticeGroupRepository.Add(eventPracticeGroup);
    */

    var eventId = EventScheduleRepository.GetById(Convert.ToInt32(Request.QueryString["EventScheduleId"])).EventId;
    var theEvent = new Event() { Id = eventId };
    EventRepository.Repository.UnitOfWork.Context.AttachTo("Events",theEvent);
    var practiceGroupCache = new PracticeGroupCache() { Id = eventPracticeGroup.PracticeGroupCacheId };
    practiceGroupCache.Region = new Region() { Id = eventPracticeGroup.PracticeGroupCache.RegionId };
    eventPracticeGroup.PracticeGroupCache = practiceGroupCache;
    EventPracticeGroupRepository.Add(eventPracticeGroup);
    EventPracticeGroupRepository.Save();
    return RedirectToAction("Index");
}

Anyway... as you can see, I've just tried using stub objects (no help), and I've also tried actually fetching and setting the objects. The error I get is:

Cannot insert the value NULL into column 'Name', table 'XXXX.dbo.Regions'; column does not allow nulls. INSERT fails. The statement has been terminated.

Obviously name is not a key field. I have checked the EDMX XML - only the Id (primary key columns) have StoreGeneratedPattern set to Identity, as they should (they are int32 identity columns). Not a single foreign key has StoreGeneratedPattern set to identity.

if I set Regions.Name to allow nulls, PracticeGroupCaches.Description throws the same error. It seems that every linked object gets set to null. I did have a look with the debugger, when I used the now commented out code, nothing was null and everything had a value. I even got the RegionRepository to return all of the regions, just to see if one of them somewhere had a null name. None did. There are only 2 in my test DB. Our object context is shared per HTTP request.

Please can anyone help. At this point I would settle for using the dirtiest workaround as long as it worked.

Regards, Jonathan.

Look what happens when you call this line:

EventPracticeGroupRepository.Add(eventPracticeGroup);

You are adding a new eventPracticeGroup to the context. But eventPracticeGroup has the other related objects:

eventPracticeGroup -> PracticeGroupCache -> Region

And you create new objects for those:

var practiceGroupCache = new PracticeGroupCache() {
    Id = eventPracticeGroup.PracticeGroupCacheId };
practiceGroupCache.Region = new Region() {
    Id = eventPracticeGroup.PracticeGroupCache.RegionId };
eventPracticeGroup.PracticeGroupCache = practiceGroupCache;

When you add the eventPracticeGroup to the context this whole object graph gets added which means that EF considers all three objects as new which have to be added to the DB. Since you only fill the Id properties other string properties (like Name or Description) are null. Because they are not nullable in the database the INSERT command fails.

But I guess that you don't want to insert the related entities into the DB anyway but only the eventPracticeGroup. So you need to attach them to the context before you add the new object, something like:

var practiceGroupCache = new PracticeGroupCache() {
    Id = eventPracticeGroup.PracticeGroupCacheId };

EventRepository.Repository.UnitOfWork.Context.AttachTo(
   "PracticeGroupCaches",practiceGroupCache);

practiceGroupCache.Region = new Region() {
    Id = eventPracticeGroup.PracticeGroupCache.RegionId };

EventRepository.Repository.UnitOfWork.Context.AttachTo(
   "Regions",practiceGroupCache.Region);

eventPracticeGroup.PracticeGroupCache = practiceGroupCache;

EventPracticeGroupRepository.Add(eventPracticeGroup);

BTW as a side note: About this EventRepository.Repository.UnitOfWork.Context.XXX take a look at Ladislav Mrnka's answer here: EF 4.0 IsAttachedTo extension method and error An object with the same key already exists

Why is Entity Framework trying to insert NULL?, In my app, I occasionally create "throw-away" objects - e.g. a temporary entity, sometimes pre-populated with a few default values, just so I can� Browse & Discover Thousands of Book Titles, for Less.

Try to Add: [DatabaseGenerated(DatabaseGeneratedOption.None)]

On your Id field, Like:

[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }

Add entity in Entity Framework Insert Null Record - MSDN, I'm having the same problem that a few of you have had - when trying to insert a new object, EF inserts null values for some of their properties, and the insert fails � I'm having the same problem that a few of you have had - when trying to insert a new object, EF inserts null values for some of their properties, and the insert fails. First let me describe the structure of our DB.

It seems like you already found the problem and the solution. In your DB schema it seems like the columns don't allow NULL values. So either change all these columns to allow NULL or don't insert null (this is what you currently are trying to do)

Generated Values, I'm trying to insert a new Entity in EF: public class Could you please show me some code snippet about creating object and assigning value? When attempting to add a new quote I create a new quote entity and set the Agent like this: entity.Agent = (from x in entities.AgentEntities where x.AgentID == quote.AgentID select x).FirstOrDefault(); Right before SaveChanges is called I examine the object and see that all of the values are set. The Agent object has all of its values set.

How to: Handle Database Default Values - Documentation, This valid value must be assigned to new entities before they are EF will attempt to insert that value rather than generating a new one. A property is considered to have a value assigned if it is not assigned the CLR default value ( null for For example, when using SQL Server, values will be automatically� And I receive from the View the model like this (example values): kms = 222 Model.Id = 3. Then when I do the Add and SaveChanges of the Entity Framework, I get a NULL record inserted in the Model Table (that generated a new ID) and a record in the Ad Table with the new inserted Model Id. Why is this happening? Thanks.

Managing One To Many Relationships With Entity Framework Core , This article is relevant to entity models that utilize the deprecated Visual Studio The current documentation of the Data Access framework is available here. For example: the default value for the nullable Rating column from the Cars table is 10. During runtime if you try to insert a new object with null for the property� How to handle null values in entity framework ; How to handle null values in entity framework

Entity Framework: Improving Performance when Saving Data to , Entity Framework Core offers a number of approaches to the creation and to see if an object of the same type with the same key value is being tracked by the This approach results in one database operation - inserting the new book into the database. Set the Foreign Key value to null (optional relationships only) link. Retrieve data from one table and insert into another table. sql,asp.net,sql-server. INSERT INTO tbl2 ( Name ,parentId ) SELECT DISTINCT manager ,0 FROM tbl1 WHERE manager NOT IN ( SELECT employee FROM tbl1 ) INSERT INTO tbl2 SELECT DISTINCT employee ,0 FROM tbl1 UPDATE tbl2 SET parentid = parent.id FROM tbl2 INNER JOIN tbl1 ON tbl2.Name = tbl1.employee INNER JOIN tbl2

Comments
  • Thanks, some interesting notes there, I'll read through those links. even if I fetched the objects from the repository (ie the context knew they already existed in the data store), it failed with the same reason. the solution, as posted above, turned out to be to set the navigation properties to null and then assign an EntityKey. thanks for the help!
  • I did - the solution was found here: stackoverflow.com/questions/2550231/… . I wasnt trying to insert a null, thats the point.