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