asp.net-mvc - EF 4.5 Code First 复合键的 MVC 脚手架错误

标签 asp.net-mvc entity-framework ef-code-first scaffolding composite-key

我正在尝试弄清楚如何使 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。

谢谢。

最佳答案

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

阅读可用的五个实现,我们可以看出您的代码将落在 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 模板本身的影响。

Source code for the scaffolding tool.

关于asp.net-mvc - EF 4.5 Code First 复合键的 MVC 脚手架错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15634609/

相关文章:

c# - 我应该在 Controller 中使用普通方法吗?

entity-framework - 具有实体数据模型的 Active Directory

c# - Entity Framework 6 - 该类型已配置为实体类型。它不能重新配置为复杂类型

c# - 键列具有不同名称时的实体拆分?

c# - 在客户端上显示服务器日期和服务器时间

c# - Asp Web Api 异步操作 - 404 错误

c# - 如何在 ASP.NET MVC Controller 中使用 Automapper 配置

c# - 如何确定 Expression<Func<T, object>> 是否对 EntityFramework .Include 有效

sql-server-2008-r2 - Entity Framework 代码第一基类未映射到数据库

asp.net - 默认情况下,我们可以让 Entity Framework Code First 创建除 LocalDB 之外的 SQL Server Express 数据库吗?