我有一个非常简单的 C# 类,其中包含一个主键。我正在使用代码优先的 EF 6,我有两个问题:
如何在代码优先中将主键作为
Identity(以及如何不使其成为身份)?我的一些类需要 PK 作为身份(添加时自动递增),一些需要通过代码分配。当我尝试使用以下方法将类保存到数据库时:
// This code is actually wrapped by a BusinessContext Class to encapsulate the ORM representation context.Costumers.Add(costumer); //exception is here! context.SaveChanges();我的类在
Add方法上出现以下异常:One or more validation errors were detected during model generation:
M.Costumer: : EntityType 'Costumer' has no key defined. Define the key for this EntityType.
Costumers: EntityType: EntitySet 'Costumers' is based on type 'Costumer' that has no keys defined.
这是类本身:
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],那怎么会出现异常说没有key呢?
请您参考如下方法:
Entity Framework 必须为任何 [Key] 属性提供 getter 和 setter。
如果您想指定 EF 您将为该字段生成值,您可以使用 [DatabaseGeneratedOption.None]。
DatabaseGeneratedOption枚举有 3 个不同的值:
- 计算的——当插入或更新一行时,数据库生成一个值。
- 标识——当插入一行时,数据库生成一个值。
- 无 -- 数据库不生成值。
键值的默认值为 DatabaseGeneratedOption.Identity
