I am trying to figure out how to make MVC Scaffolding to work with composite/complex key.
I have the following table:
public class Data
{
[Key, Column(Order = 0)]
[ForeignKey("Note")]
[Display(Name = "Note id")]
public int NoteId { get; set; }
[Key, Column(Order = 1)]
[ForeignKey("Member")]
[Display(Name = "Member id")]
public int MemberId { get; set; }
[Display(Name = "Description")]
public string Description { get; set; }
[Display(Name = "Note")]
public virtual Note Note { get; set; }
[Display(Name = "Member")]
public virtual Member Member { get; set; }
}
When I execute the line for scaffolding:
Scaffold Controller Data -Repository
I receive the following error:
Get-PrimaryKey : Cannot find primary key property for type
Pro.Web.Models.Data'. Multiple properties appear to be
primary keys: NoteId, MemberId
What could be the solution for this problem? I use Visual Studio 2012.
Thanks.
The class PrimaryKeyLocation
under the T4Scaffolding.Core.PrimaryKeyLocators
namespace has a list of IPrimaryKeyLocator
interfaces that are implemented on the PrimaryKeyLocation.cs file itself.
Reading the five implementations available, one can tell that your code will fall on the KeyAttributePropertyLocator
implementation returning both members marked with the [Key] attriubute, but the GetPrimaryKeyCmdlet.cs
that is run from the T4 engine and that calls the PrimaryKeyLocation
class has the following implementation:
switch (primaryKeyProperties.Count)
{
case 0:
// Code when no key is found
case 1:
// Code when one key is found
default:
// Code when more than one key is found
WriteError(string.Format("Cannot find primary key property for type '{0}'.
Multiple properties appear to be primary keys: {1}",
foundClass.FullName, primaryKeyPropertyNames));
}
Therefore, as the switch statement does not deal with more than one key, composite keys are not supported. One way out of this is to implement the case for composite keys, but I would not know the implications of that on the t4 templates themselves.