I have a form that creates a new brand. The user chooses a name, image, and website url for the brand and hits submit. The edit scenario works the same way. The issue I'm having is when creating a new brand, the correct imageId is being posted, and right up to SaveChanges() in my action its correct. When I check the new row in the database, the ID has been doubled and then some. (for example if I submit 37, the database changes it to 78, 38 to 80 etc.) I'm stumped as to why this is happening. Here's my action:
[HttpPost]
public ActionResult NewBrand(Brand brand)
{
try
{
brand.BrandName = Request.Form["BrandName"];
brand.BrandImageId = int.Parse(Request.Form["Image.ImageId"]);
brand.BrandWebsite = Request.Form["BrandWebsite"];
_entities.Brands.AddObject(brand);
_entities.SaveChanges();
return RedirectToAction("Brands");
}
catch (Exception ex)
{
var script = "alert(" + ex.Message + ")";
return JavaScript(script);
}
}
And heres an example POST from firebug
Parametersapplication/x-www-form-urlencoded
BrandName Sample Brand
BrandWebsite www.somewebsite.com
Image.ImageId 37
Source
Content-Type: application/x-www-form-urlencoded Content-Length: 72
BrandName=Sample+Brand&Image.ImageId=37&BrandWebsite=www.somewebsite.com
I am using the entity framework and built my database using the wizards in visual studio. My brands table has the foreign key ImageId and i have an image table with the primary key ImageId, they have a one to many relationship. Any ideas?
edit
I created the entity framework object by right-clicking my models folder and adding a new .edmx file. And then I right clicked in the design view and hit "update from database" and it created a model from the tables I created. I haven't done any special configuration or setup beyond this, nor am I using the repository pattern (yes, that means I have data access code in my controllers, I am refactoring this weekend) which I learned after starting this project.
_entities comes from this line at the top of the controller
private MHNHubEntities _entities = new MHNHubEntities();