asp.net-mvc-3entity-framework-4objectcontextobjectset

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?


Solution

  • 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.