Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is EF trying to insert NULL in id-column?

I am writing my project using Entity Framework 4.0 (Model first). At the beginning of the project, I faced with this problem: I am trying to insert the filled object in the database, but I get an exeption:

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

Code:

    Category usingCategory = new Category("Using Forums", "usingforums", 0);     using (Context)     {         Context.Categories.AddObject(usingCategory);         Context.SaveChanges();     } 

I checked this object, and I am sure that it is filled.

Just in case:

public Category(string name, string urlName, int index) {     CategoryId = Guid.NewGuid();     Name = name;     UrlName = urlName;     CategoryIndex = index; } 

What is going on?

like image 586
Kovpaev Alexey Avatar asked Jan 13 '12 18:01

Kovpaev Alexey


People also ask

Can identity column have NULL values?

As far as I know, as the identity column of the database, we cannot set Allow Nulls= true. because it is the identification column, used to identify the only record. For security purposes, Guid could be used as an Identity column.

How do I get an ID after inserting EF core?

EF execute each INSERT command followed by SELECT scope_identity() statement. SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. The above example will execute the following SQL in the database. WHERE @@ROWCOUNT = 1 AND [StudentID] = scope_identity();

How do you INSERT data into a NULL 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?

ORA-01400: cannot insert null into (string) is a specific error to the null value in Oracle. According to Oracle, a null value can appear in columns of any datatype as long as it is not set to the value “not null” or is restricted by primary key integrity constraints.


1 Answers

Have a look at this: https://stackoverflow.com/a/5338384/171703 - entity framework might be assuming that your CategoryId field is an identity and therefore passing null to the database expecting it to fill it for you.

like image 198
akiller Avatar answered Oct 05 '22 23:10

akiller