Why is this throwing a NULL value exception?
Asked Answered
K

1

8

For some reason I am getting the following error at the db.SaveChanges(); instruction:

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

Controller code:

[HttpPost]
[Authorize]
public ActionResult Create(Portfolio portfolio)
{
    if (ModelState.IsValid)
    {
        portfolio.UserId = (Guid)Membership.GetUser().ProviderUserKey;
        db.AddToPortfolios(portfolio);
        db.SaveChanges(); 
    }
    return View("MyPortfolios");
}

I have stepped through the debugger and confirmed that UserID is being populated.

Update:

I have tried changing db.AddToPortfolios(portfolio); to db.Portfolios.AddObject(portfolio); but it is still having the same problem.

Portfolios is an ObjectSet, should I use the Attach() method?

Kristykristyn answered 7/7, 2011 at 15:23 Comment(2)
Is UserId a foreign key to another table or is it the primary key on your Portfolio table (or both for perhaps 1-to-1 relationship)? Do you really use EF 4.1? I'm wondering because db seems to be an ObjectContext and not a DbContext in your code.Lintwhite
You are correct I am using version 4 not 4.1. I used a model first approach to create the database. UserId is the primary key for Portfolio. Portfolio has a many to many relationship with another table. It looks like entity framework created a join table in the actual database to facilitate the many to many.Kristykristyn
L
8

I know this exception from only one situation, that is: UserId is not an identity column in your database but in the EF model the corresponding property is flagged as such - which means it is either explicitely attributed with DatabaseGeneratedOption.Identity or implicitely by conventions.

The problem is that in this case EF won't sent the property value to the Db (no matter if it's set or not) because it assumes that the DB will do the work to create a column value. But the Db doesn't, hence the exception.

Just a guess.

Edit:

To solve the problem you must flag UserId with DatabaseGeneratedOption.None.

Lintwhite answered 7/7, 2011 at 17:19 Comment(3)
UserId is set as DatabaseGeneratedOption.Identity. Should I change this to something else?Kristykristyn
The corresponding db column is UserId (PK, uniqueidentifier, not null)Kristykristyn
@ZeroDivide: Yes, DatabaseGeneratedOption.None is the solution. uniqueidentifier/guid columns are not autogenerated in SQL Server.Lintwhite

© 2022 - 2024 — McMap. All rights reserved.