.NET

Define 2 keys in an MVC3 model object

Last I was converting an application into MVC3. But when I came to the point where I needed to create an object that contained 2 keys. I could not do this with following code:
I always received the error message: Unable to determine composite primary key ordering for type ‘Project.Models.ModelObject’. Use the ColumnAttribute or the HasKey method to specify an order for composite primary keys.

public class ModelObject
{
	[Key]
	[Required]
	public decimal FirstKey { get; set; }

	[Key]
	[Required]
	public int SecondKey { get; set; }
}

The solution was actually in the error message itself but I saw there were alot of people having troubles finding a solution.
You need to create an attribute Column to define the keys.
Here is the code of my model that solved my multiple key problem.

public class ModelObject
{
	[Key]
	[Required]
	[Column(Order=0)]
	public decimal FirstKey { get; set; }

	[Key]
	[Required]
	[Column(Order=1)]
	public int SecondKey{get; set; }
}

Hopefully this saved you alot of time searching for an answer.

Leave a Reply

Your email address will not be published. Required fields are marked *