2

我试图弄清楚如何使 MVC 脚手架与复合/复合键一起工作。

我有下表:

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; }
}

当我执行脚手架行时:

Scaffold Controller Data -Repository

我收到以下错误:

Get-PrimaryKey : Cannot find primary key property for type
Pro.Web.Models.Data'. Multiple properties appear to be 
                        primary keys: NoteId, MemberId

这个问题的解决方案是什么?我使用 Visual Studio 2012。

谢谢。

4

1 回答 1

5

PrimaryKeyLocation命名空间下的类具有在 PrimaryKeyLocation.cs 文件本身上实现T4Scaffolding.Core.PrimaryKeyLocators的接口列表。IPrimaryKeyLocator

阅读可用的五种实现,可以看出您的代码将落在KeyAttributePropertyLocator返回标有 [Key] 属性的两个成员的实现上,但是GetPrimaryKeyCmdlet.cs从 T4 引擎运行并调用PrimaryKeyLocation该类的实现具有以下实现:

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));
}

因此,由于 switch 语句不处理多个键,因此不支持复合键。解决这个问题的一种方法是实现复合键的情况,但我不知道它对 t4 模板本身的影响。

脚手架工具的源代码。

于 2013-03-26T12:32:22.937 回答