Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot INSERT NULL into Column on Remove

I'm executing a Remove() using Entity Framework. When I try to run SaveChanges(), I'm told that I can't insert NULL into a column that doesn't allow it. This is strange to me, since I'm not doing any INSERT, and I checked each of the 30 existing entries to find that it shouldn't be trying to save the table with null in that column.

Here is the code in question:

var user = db.AspNetUsers.FirstOrDefault(u => u.Id == userId);
if (user != null)
{
    var itemsToRemove = user.ItemXrefs.Where(i => !itemIDs.Contains(i.ItemID)).ToList();

    foreach (var xref in itemsToRemove)
    {
        user.ItemXrefs.Remove(xref);
    }

    db.SaveChanges();
    //...
}
like image 363
muttley91 Avatar asked Mar 02 '15 00:03

muttley91


People also ask

How do I insert a NULL into a column?

You also can specify the NULL keyword in the VALUES clause to indicate that a column should be assigned a NULL value. The following example inserts values into three columns of the orders table: INSERT INTO orders (orders_num, order_date, customer_num) VALUES (0, NULL, 123);

Can not insert null value?

You cannot insert NULL values in col1 and col2 because they are defined as NOT NULL. If you run the script as is, you will receive an error. To fix this code, replace NULL in the VALUES part with some values (for example, 42 and 'bird' ).

Can we insert null value in primary column?

Primary key constraintsNULL values are not allowed. If the column(s) contain NULL values, the system will not add the primary key constraint. See ALTER TABLE statement for more information.

Can we insert NULL in foreign key column?

Yes. Foreign key can take Null .


1 Answers

Try this instead:

itemXrefSet = db.Set<ItemXref>();
foreach (var xref in itemsToRemove)
{
    itemXrefSet.Remove(xref);
}
db.SaveChanges();

This should delete the cross-referencing entity from the gerund table as well as the relationship between the two entities it links together.

The reason you ran into an error the way you tried to do it was because EntityFramework thought you just wanted to remove the relationship without removing the related entity. When EF does this it tries to set the foreign key column in the dependent table to NULL. The way around this is to either relate the table row with another user by changing the UserId column value, or deleting the table row, since you can't set a required column value to NULL.

like image 63
danludwig Avatar answered Oct 02 '22 16:10

danludwig