views:

898

answers:

4

I am fairly new to the Entity Framework and am in the process of building my first MVC application. I'm implementing a Create View for a simple Entity however, I am having problems with the (SQL Express 2005) Identity column primary key. As I understand it the Framework should handle the Identity column and let the SQL database generate the ID value.

When I try to Save using the Create View without setting the ID value I get a "Value is Required" error. If I specify any value for ID it saves back to the database using the Identity value from the database - ie. rather than the value I have specified so the T-SQL is obviously being generated correctly once it gets that far.

The Identity property is set on the ID column in the database and the StoreGeneratedPattern is set to "Identity" in the model (see below):-

Property Name="ID" Type="int" Nullable="false" StoreGeneratedPattern="Identity"

Am I missing something? How do I tell the Model that a value is not required for this column?

A: 

You don't say where the "Value is Required" error is coming from. Integer values in your client model will default to zero, so there will always be a value. Without seeing a stack, my wild guess is that the error is coming from somewhere else. Look at the stack when you see the error, and figure out which part of your application is raising it.

Craig Stuntz
You are right. It's nothing to do with the database. UpdateModel(entity) is failing when it receives the FormCollection. Trying it another way ModelState.IsValid = false when passed the entity. "A value is required" validation being returned for the ID field.
A: 

Mystery solved. It seems the issue was a result of my naming convention of always using "ID" as the column name for an ID column.

When I was calling

http://.../Vacancy/Create

The routing engine is picking this up as

Action = Create; ID = ""

from the MapRoute "{controller}/{action}/{id}"

Changed the identity column name to "VacancyID" in the model and voila everything works as it should.

A: 

I would create a custom route, that's what they are for anyways...

mhenrixon
A: 

If you don't want to change your database schema you can add routing rule without id parameter

routes.MapRoute(
   "Create",
   "{controller}/Create",
    new { action = "Create" }
);
Emir