【问题标题】:EntityType has no key defined. [Key] is presentedEntityType 没有定义键。 [Key] 出现
【发布时间】:2013-10-12 14:28:41
【问题描述】:

实体

public class Region
{
    [Key]
    public int ID;
    public string Name; 
    public string Description;
}

型号

public class RegionModel
{   [Key]
    public int ID { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }
}

错误

System.Data.Edm.EdmEntityType: : EntityType 'Region' 没有键 定义。定义此 EntityType 的键。
System.Data.Edm.EdmEntitySet: EntityType: EntitySet ‘Regions’ 是基于 在没有定义键的类型“Region”上。

【问题讨论】:

    标签: asp.net-mvc entity-framework


    【解决方案1】:

    您的类字段需要更改为属性,EF 才能正确使用该类;

    public class Region
    {
        [Key]
        public int ID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }
    

    【讨论】:

      【解决方案2】:
      public class Region
      {
          [Key]
          public int RegionId{get;set;}
          public string Name{get;set;} 
          public string Description{get;set;}
      }
      
      public class RegionModel
      {   [Key]
          public int RegionModelId { get; set; }
      
          public string Name { get; set; }
      
          public string Description { get; set; }
      }
      

      如果你有ClassNameId这样的属性,它就可以工作。你现在甚至可以删除[Key]属性。

      【讨论】:

        【解决方案3】:

        也许对您的问题有一个奇怪的答案。但请确保您的项目首先编译。当我在没有编译项目的情况下添加数据注释时,我得到了同样的错误。

        我认为代码是通过某种反射生成的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-04-02
          • 2016-03-16
          • 2013-08-04
          • 2012-12-10
          • 2016-09-26
          • 1970-01-01
          相关资源
          最近更新 更多