【问题标题】:MVC Entity Framework cannot find the keyMVC 实体框架找不到密钥
【发布时间】:2014-01-22 13:56:34
【问题描述】:

我已经从我的数据库中生成了我的模型。其中一个模型看起来像:

namespace LV.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Ac
    {
        public int IdAc { get; set; }
        public int IdEmp { get; set; }
        public Nullable<System.DateTime> dtd{ get; set; }
        public Nullable<int> Sn{ get; set; }
        public Nullable<bool> A{ get; set; }
        public Nullable<int> IdSi{ get; set; }
        public Nullable<bool> Gest{ get; set; }
        public Nullable<int> IdResp { get; set; }
        public string SigXML { get; set; }
        public Nullable<bool> Read { get; set; }
        public Nullable<System.DateTime> EndDate{ get; set; }
        public string dpd{ get; set; }
        public string gda { get; set; }
        public string typeaq { get; set; }
        public byte[] attch { get; set; }
        public string exten { get; set; }

        public virtual AC emps { get; set; }
    }
}

当我尝试创建一个控制器时,它显示has no key defined。我尝试了其他帖子中的解决方案,其中说我必须使用[Key],它会创建我的控制器,但是当我运行项目时,它会抛出另一个异常,上面写着the following table cannot be created。它说是因为该表已经存在。

我使用 Visual Studio 2013 Express 和 EF 6 &lt;section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /&gt;

主键是idAc。它也是身份。如果我检查图表,就是它所说的。

据我所见,映射很好。我在图中标识的所有键、关系、主键、身份字段。

【问题讨论】:

  • 数据库中的主键是哪一列?你真的有主键吗?
  • 我编辑了这篇文章。请检查底部。
  • 你的编辑没有帮助..你的数据库表真的有主键吗??
  • 是的,我的表有一个主键,它也是一个身份。

标签: c# asp.net-mvc entity-framework


【解决方案1】:

试试这个:

[Key]
[Column("idAc")]
public int IdAc { get; set; }

我怀疑映射可能区分大小写,因此,当您指定 [Key] 时,EF 只会查找名为 IdAc 的列,但没有找到。

我了解您正在使用 EDM 设计器,因此如果这不能解决问题,则可能是 EDM 设计器弄乱了映射。尝试将属性重命名为与列相同的名称(即idAc)或检查this workaround

另外,请注意,如果您不使用[Key] 或Fluent API 的.HasKey 方法来指示哪个属性是键,则默认情况下EF uses the code-convention 使用与实体同名的属性(最后有或没有“Id”)。

【讨论】:

  • 所有列的名称与数据库中的列相同。我不知道 EDM 设计器是否弄乱了映射,但我知道它可以很好地读取表结构和关系。
【解决方案2】:

我找到了解决方案。当我生成 edmx 文件时,他问我是否要保存连接字符串。那时我选择不保存它。后来我发现在我的 edmx 属性中有一个空的连接字符串。

我删除了 edmx 并生成了一个新的,这次保存了连接字符串。从这一刻起,一切顺利。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 2013-09-25
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    相关资源
    最近更新 更多