c# - "EntityType has no key defined"异常,尽管键是用 HasKey 定义的

标签 c# entity-framework model ef-code-first entity-framework-5

使用 EF 5(首先对代码进行逆向工程),我的模型工作正常,直到它突然停止。

\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'ProjectsDate' has no key defined. Define the key for this EntityType.

\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'ProjectsRisk' has no key defined. Define the key for this EntityType.

我使用流畅的 API 而不是属性定义了一个键,这是我的 ProjectsDates 类。

public partial class ProjectsDate
{
    public string OSProjectCode { get; set; }
    public Nullable<System.DateTime> TargetStart { get; set; }
    public Nullable<System.DateTime> EndDateOriginal { get; set; }
    public Nullable<System.DateTime> EndDateChangeControl { get; set; }
    public Nullable<System.DateTime> EndDateActual { get; set; }
    public Nullable<System.DateTime> GoLiveAgreed { get; set; }
    public Nullable<System.DateTime> GoLiveActual { get; set; }
    public virtual Project Project { get; set; }
}
public class ProjectsDateMap : EntityTypeConfiguration<ProjectsDate>
{
    public ProjectsDateMap()
    {
        // Primary Key
        this.HasKey(t => t.OSProjectCode);

        // Properties
        this.Property(t => t.OSProjectCode)
            .IsRequired()
            .HasMaxLength(10);

        // Table & Column Mappings
        this.ToTable("ProjectsDates");
        this.Property(t => t.OSProjectCode).HasColumnName("OSProjectCode");
        this.Property(t => t.TargetStart).HasColumnName("TargetStart");
        this.Property(t => t.EndDateOriginal).HasColumnName("EndDateOriginal");
        this.Property(t => t.EndDateChangeControl).HasColumnName("EndDateChangeControl");
        this.Property(t => t.EndDateActual).HasColumnName("EndDateActual");
        this.Property(t => t.GoLiveAgreed).HasColumnName("GoLiveAgreed");
        this.Property(t => t.GoLiveActual).HasColumnName("GoLiveActual");

        // Relationships
        this.HasRequired(t => t.Project)
            .WithOptional(t => t.ProjectsDate);

    }
}

为什么 EF 看不到我的 Fluent API 映射?

最佳答案

出于某种原因(可能是错误),FluentAPI 需要以约定方式定义 key - 即 - ClassName + Id,或者在您的情况下:

ProjectsDateId

这样,EF 创建的元数据就可以确认它是相关的。 很烦人但是...

关于c# - "EntityType has no key defined"异常,尽管键是用 HasKey 定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16461941/

相关文章:

entity-framework - EF4 CTP5 : DbContext inheritance

python - 如何在django中根据结束日期自动删除记录

asp.net - 将多个模型发送到单个 View 实例

c# - 64 位 Windows 服务器中的 Sybase 驱动程序错误

c# - EntityFramework 插入速度非常慢,数据量大

c# - CaSTLe Windsor 重建实例

c# - 在 Code First MVC 应用程序中查询 AspNet Identity 表

php - 如何仅更新 Yii 中事件记录的特定字段?

c# - 反序列化 JSON 项目

c# - 在 C# 中截断 double 值的位数