如何在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 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());
[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());
威孚半导体技术
2024-08-19 广告
2024-08-19 广告
威孚(苏州)半导体技术有限公司是一家专注生产、研发、销售晶圆传输设备整机模块(EFEM/SORTER)及核心零部件的高科技半导体公司。公司核心团队均拥有多年半导体行业从业经验,其中技术团队成员博士、硕士学历占比80%以上,依托丰富的软件底层...
点击进入详情页
本回答由威孚半导体技术提供
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询