实体框架主键异常

时间:2015-03-12 04:33:42

标签: c# entity-framework

我有一个非常简单的C#类,它包含一个主键。我使用EF 6代码优先,我有两个问题:

  1. 如何在代码优先(以及如何不使其成为身份)中将主键设为Identity?我的一些类需要PK作为标识(添加时自动增加),有些需要通过代码分配。

  2. 当我尝试使用以下方法将类保存到数据库时:

    // This code is actually wrapped by a BusinessContext Class to encapsulate the ORM representation
    context.Costumers.Add(costumer); //exception is here!
    context.SaveChanges();
    

    我的课程在Add方法上获得以下异常:

      

    在模型生成期间检测到一个或多个验证错误:

         

    M.Costumer :: EntityType'Costumer'没有定义键。定义此EntityType的键   客户:EntityType:EntitySet'Costumers'基于没有定义键的'Costumer'类型。

  3. 这就是班级本身:

    using Microsoft.Practices.Prism.Mvvm;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MyApp.Models
    {
        public class Costumer : BindableBase
        {
            private string name;
            private string city;
            private Estado state;
            private int costumerId;
    
            [Required]
            [StringLength(500)]        
            public string Name
            {
                get { return this.name; }
                set { SetProperty(ref name, value); }
            }
    
            [Required]
            [StringLength(500)]
            public string City
            {
                get { return this.city; }
                set { SetProperty(ref city, value); }
            }
    
            [Required]
            public State State
            {
                get { return this.state; }
                set { SetProperty(ref state, value); }
            }
    
            [Required]
            [Key]
            public int CostumerId
            {
                get { return this.costumerId; }            
            } 
        }
    }
    

    这个班的确有一个[Key],那么怎么会有一个例外,说没有钥匙呢?

2 个答案:

答案 0 :(得分:4)

实体框架必须具有任何[Key]属性的getter和setter。

如果您想为EF指定您将为此字段生成值,则可以使用[DatabaseGeneratedOption.None]

DatabaseGeneratedOption枚举有3个不同的值:

  • 已计算 - 数据库在插入或更新行时生成值。
  • Identity - 数据库在插入行时生成值。
  • 无 - 数据库不生成值。

键值的默认值为DatabaseGeneratedOption.Identity

答案 1 :(得分:0)

在密钥中使用[DatabaseGeneratedOption.None]属性。