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?
UserId
a foreign key to another table or is it the primary key on yourPortfolio
table (or both for perhaps 1-to-1 relationship)? Do you really use EF 4.1? I'm wondering becausedb
seems to be anObjectContext
and not aDbContext
in your code. – LintwhiteUserId
is the primary key forPortfolio
.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