Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this throwing a NULL value exception?

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?

like image 966
Stephen__T Avatar asked Jul 07 '11 15:07

Stephen__T


1 Answers

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.

like image 112
Slauma Avatar answered Sep 24 '22 01:09

Slauma