I am using Entity Framework 5 and MVC 4, with .NET 4.5, using First code migrations. I have foreign keys between two objects in a ratio of 1 to zero or -1. When I try to create a record for Jogger, everything explodes. I get error messages:
- Foreign key is a null reference
- dbo.Jogger does not exist
- Unhandled exception ... no metadata.
When I launch EF Viewer, the navigation relationship is perfect. No Fluent API code is currently in use.
User class
[Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } public string UserName { get; set; } // Other properties public int? JoggerId { get; set; } public virtual Jogger Jogger { get; set; }
Jogger class
[ForeignKey("UserId")] public int JoggerId { get; set; } public virtual UserProfile UserId { get; set; }
When the JoggerController is generated, it creates this code for the Get and Post methods:
// GET: /Jogger/Create public ActionResult Create() { ViewBag.JoggerId = new SelectList(db.UserProfiles, "UserId", "UserName"); return View(); } // // POST: /Jogger/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Jogger jogger) { if (ModelState.IsValid) { db.Jogger.Add(jogger); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.JoggerId = new SelectList(db.UserProfiles, "UserId", "UserName", jogger.JoggerId); return View(jogger); }
In the Jogger / Create view, there are no fields for the JoggerId or UserId according to the generated code.
It usually doesn't work in the (ModelState.IsValid) part of the code, where Output shows JoggerId = 0 and UserId = null.
I did not see this behavior in the Contoso University tutorial on asp.net, and I also studied the MSDN Learn EF website. I can not solve this problem. Your advice is welcome.
source share