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();
//...
}
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);
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' ).
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.
Yes. Foreign key can take Null .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With