C# 如何在配置文件中的EF中放置唯一键约束?
我正在配置文件的项目中使用EF。我有Employee的域类,它只有属性(没有数据注释或任何关系) 我想为用户名编写唯一的键约束代码 请看下面的员工类别C# 如何在配置文件中的EF中放置唯一键约束?,c#,entity-framework,entity-framework-4,C#,Entity Framework,Entity Framework 4,我正在配置文件的项目中使用EF。我有Employee的域类,它只有属性(没有数据注释或任何关系) 我想为用户名编写唯一的键约束代码 请看下面的员工类别 public class Employee : IEntity { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Gender
public class Employee : IEntity
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public string MobileNo { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
using System.Data.Entity.ModelConfiguration;
class Configurations
{
public class EmployeeConfigration : EntityTypeConfiguration<Employee>
{
public EmployeeConfigration()
{
this.Property(x => x.FirstName).IsRequired().HasMaxLength(50);
this.Property(x => x.LastName).HasMaxLength(50);
// I want to write code for unique key constrain,for username property.
}
}
}
我有一个配置类,它包含employee类的所有验证
public class Employee : IEntity
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public string MobileNo { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
using System.Data.Entity.ModelConfiguration;
class Configurations
{
public class EmployeeConfigration : EntityTypeConfiguration<Employee>
{
public EmployeeConfigration()
{
this.Property(x => x.FirstName).IsRequired().HasMaxLength(50);
this.Property(x => x.LastName).HasMaxLength(50);
// I want to write code for unique key constrain,for username property.
}
}
}
使用System.Data.Entity.ModelConfiguration;
类配置
{
公共类EmployeeConfiguration:EntityTypeConfiguration
{
公共雇员配置()
{
this.Property(x=>x.FirstName).IsRequired().HasMaxLength(50);
this.Property(x=>x.LastName).HasMaxLength(50);
//我想为用户名属性的唯一键约束编写代码。
}
}
}
如何编写用户名属性的唯一键约束 EF不支持唯一约束,但它支持唯一索引。没有直接的方法用fluentapi映射它们,但是您可以利用fluentapi方法添加属性,如下所示
Property(x => x.UserName)
.HasColumnAnnotation("Index", new IndexAttribute() {IsUnique = true});
编辑
正如Max Brodin在其评论中指出的,这仅在EF 6.1中得到支持。请尝试此代码
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure.Annotations;
...
this.Property(t => t.UserName)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(
new IndexAttribute("IX_UserName", 1) { IsUnique = true }));
编辑:使用语句添加它没有显示IndexAttribute属性,我必须添加哪个库?这只适用于从版本6.1开始的EF,请检查尝试使用System.ComponentModel.DataAnnotations.Schema添加;运行应用程序时出错,
IndexAnnotationSerializer无法序列化“IndexAttribute”类型的对象。只能序列化“IndexAnnotation”对象。
上面的代码不正确。IndexAttribute必须包装在IndexAnnotation中。见马克斯·布罗丁的评论。正确。给定错误当前上下文中不存在名称“IndexAnnotation”
您需要使用System.Data.Entity.Infrastructure.Annotations添加;