如何在EF CodeFirst中使用唯一约束

如题所述

第1个回答  2014-12-23
使用唯一约束的两种方式:

方式1 自定义唯一约束

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class UniqueAttribute : ValidationAttribute
{
public override Boolean IsValid(Object value)
{
//校验数据库是否存在当前Key
return true;
}
}

View Code

在Model类中使用

public class Email
{
[Key]
public int EmailID { get; set; }

public int PersonId { get; set; }

[Unique]
[Required]
[MaxLength(100)]
public string EmailAddress { get; set; }
public virtual bool IsDefault { get; set; }
public virtual Boolean IsApprovedForLogin { get; set; }
public virtual String ConfirmationToken { get; set; }

[ForeignKey("PersonId")]
public virtual Person Person { get; set; }
}

View Code

方式2 扩展DataBaseSetInitializer 使用Sql语句添加

public class MyInitializer : CreateDatabaseIfNotExists<MyContext>
{
protected override void Seed(MyContext context)
{
context.Database.ExecuteSqlCommand("CREATE UNIQUE INDEX IX_Category_Title ON Categories (Title)");
}
}

View Code

在DbContext中使用

Database.SetInitializer<MyContext>(new MyInitializer());

View Code

方式3 扩展IDatabaseInitializer

public class Initializer : IDatabaseInitializer<myEntities>
{
public void InitializeDatabase(myEntities context)
{
if (System.Diagnostics.Debugger.IsAttached && context.Database.Exists() && !context.Database.CompatibleWithModel(false))
{
context.Database.Delete();
}

if (!context.Database.Exists())
{
context.Database.Create();

var contextObject = context as System.Object;
var contextType = contextObject.GetType();
var properties = contextType.GetProperties();
System.Type t = null;
string tableName = null;
string fieldName = null;
foreach (var pi in properties)
{
if (pi.PropertyType.IsGenericType && pi.PropertyType.Name.Contains("DbSet"))
{
t = pi.PropertyType.GetGenericArguments()[0];

var mytableName = t.GetCustomAttributes(typeof(TableAttribute), true);
if (mytableName.Length > 0)
{
TableAttribute mytable = mytableName[0] as TableAttribute;
tableName = mytable.Name;
}
else
{
tableName = pi.Name;
}

foreach (var piEntity in t.GetProperties())
{
if (piEntity.GetCustomAttributes(typeof(UniqueAttribute), true).Length > 0)
{
fieldName = piEntity.Name;
context.Database.ExecuteSqlCommand("ALTER TABLE " + tableName + " ADD CONSTRAINT con_Unique_" + tableName + "_" + fieldName + " UNIQUE (" + fieldName + ")");
}
}
}
}
}
}
}

View Code

在DbContext中使用

System.Data.Entity.Database.SetInitializer<MyApp.Models.DomainModels.myEntities>(new MyApp.Models.DomainModels.myEntities.Initializer());本回答被提问者和网友采纳

如何在EF CodeFirst中使用唯一约束
方式1 自定义唯一约束 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]public class UniqueAttribute : ValidationAttribute { public override Boolean IsValid(Object value){ \/\/校验数据库是否存在当前Key return true;} } View Code 在Model类中使用 public class E...

microsoft entity framework 包含哪些功能
b、支持唯一约束。它允许你在实体内除主键外额外标识一个键,将他们用作外键。2、行为(Behavior)改变 在EF6和前期的版本中,顶层API就有很多不直观的行为,虽然EF7尽可能是保持顶层API的相同,但仍去掉了一些限制并添加了一些我们期待的行为。什么意思呢?这听起来有点迷糊,举个例子来说明吧,以前的...

东方神起歌曲
1st Single-Hug 2nd Single-The Way U Are 3nd Single-Christmas Gift From TVXQ 05 Summer Single Album-Hi ya ya Special Single-Show Me Your Love [Single]旅行记 Anyband Digital Single 2006年特别专辑-东方的斗魂 【韩文专辑】[1st Album]Tri-Angle 2004\/10\/13 01 ) 믿어...

如何在EF CodeFirst中使用唯一约束
方式1 自定义唯一约束 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]public class UniqueAttribute : ValidationAttribute { public override Boolean IsValid(Object value){ \/\/校验数据库是否存在当前Key return true;} } View Code 在Model类中使用 public class E...

如何在EF CodeFirst中使用唯一约束
使用唯一约束的两种方式:方式1 自定义唯一约束 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]public class UniqueAttribute : ValidationAttribute { public override Boolean IsValid(Object value){ \/\/校验数据库是否存在当前Key return true;} } View Code 在Model...

如何在EF CodeFirst中使用唯一约束
定义唯一约束 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]public class UniqueAttribute : ValidationAttribute { public override Boolean IsValid(Object value){ \/\/校验数据库是否存在当前Key return true;} } 在Model类中使用 public class Email { [Key]public...

如何在EF CodeFirst中使用唯一约束
定义唯一约束 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]public class UniqueAttribute : ValidationAttribute { public override Boolean IsValid(Object value){ \/\/校验数据库是否存在当前Key return true;} } 在Model类中使用 public class Email { [Key]public...

如何在EF CodeFirst中使用唯一约束
定义唯一约束 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]public class UniqueAttribute : ValidationAttribute { public override Boolean IsValid(Object value){ \/\/校验数据库是否存在当前Key return true;} } View Code 在Model类中使用 public class Email { [...

如何在EF CodeFirst中使用唯一约束
定义唯一约束 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]public class UniqueAttribute : ValidationAttribute { public override Boolean IsValid(Object value){ \/\/校验数据库是否存在当前Key return true;} } View Code 在Model类中使用 public class Email { [...

如何在EF CodeFirst中使用唯一约束
自定义唯一约束 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]public class UniqueAttribute : ValidationAttribute { public override Boolean IsValid(Object value){ \/\/校验数据库是否存在当前Key return true;} } ...

相似回答