一直用EF Fluent Api 做MapConfiguration

所以遇到了唯一约束这个瓶颈

使用唯一约束的两种方式:

方式1 自定义唯一约束

[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 int EmailID { get; set; } public int PersonId { get; set; } [Unique]
[Required]
[MaxLength()]
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; }
}


方式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)");
}
}

在DbContext中使用
Database.SetInitializer<MyContext>(new MyInitializer());


方式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()[]; var mytableName = t.GetCustomAttributes(typeof(TableAttribute), true);
if (mytableName.Length > )
{
TableAttribute mytable = mytableName[] as TableAttribute;
tableName = mytable.Name;
}
else
{
tableName = pi.Name;
} foreach (var piEntity in t.GetProperties())
{
if (piEntity.GetCustomAttributes(typeof(UniqueAttribute), true).Length > )
{
fieldName = piEntity.Name;
context.Database.ExecuteSqlCommand("ALTER TABLE " + tableName + " ADD CONSTRAINT con_Unique_" + tableName + "_" + fieldName + " UNIQUE (" + fieldName + ")");
}
}
}
}
}
}
}

在DbContext中使用
System.Data.Entity.Database.SetInitializer<MyApp.Models.DomainModels.myEntities>(new MyApp.Models.DomainModels.myEntities.Initializer());


参考文献:http://stackoverflow.com/questions/5701608/unique-key-with-ef-code-first
 

如何在EF CodeFirst中使用唯一约束(Unique)的更多相关文章

  1. 文章翻译:ABP如何在EF core中添加数据过滤器

    原文地址:https://aspnetboilerplate.com/Pages/Documents/Articles%5CHow-To%5Cadd-custom-data-filter-ef-cor ...

  2. NULL和唯一约束UNIQUE的对应关系

    NULL和唯一约束UNIQUE的对应关系   在数据库中,NULL表示列值为空.唯一约束UNIQUE规定指定列的值必须是唯一的,值和值之间都不能相同.这个时候,就出现一个问题,NULL和NULL算是相 ...

  3. 唯一约束 UNIQUE KEY

    目录 什么是唯一约束 与主键的区别 创建唯一约束 唯一性验证 什么是唯一约束 Unique Key:它是 MySQL 中的唯一约束,是指在所有记录中字段的值不能重复出现.例如,为 id 字段加上唯一性 ...

  4. Oracle数据库中违反唯一约束的处理

    根据NULL的定义,NULL表示的是未知,因此两个NULL比较的结果既不相等,也不不等,结果仍然是未知.根据这个定义,多个NULL值的存在应该不违反唯一约束. 实际上Oracle也是如此实现的: SQ ...

  5. [mysql] 删除唯一约束unique

    alter table ot_document drop index title

  6. EF CodeFirst系列(3)---EF中的继承策略(暂存)

    我们初始化数据库一节已经知道:EF为每一个具体的类生成了数据库的表.现在有了一个问题:我们在设计领域类时经常用到继承,这能让我们的代码更简洁且容易管理,在面向对象中有“has  a”和“is a”关系 ...

  7. hibernate中怎样配置两个联合属性为唯一约束(非联合主键)

    Annotation中配置: @Table元素包括了一个schema和一个catalog属性,如果需要可以指定相应的值. 结合使用@UniqueConstraint注解可以定义表的唯一约束(uniqu ...

  8. Sybase.在PowerDesigner中如何添加-约束

    Sybase.在PowerDesigner中如何添加-约束 资料 2010-06-23 08:57:09 阅读21 评论0   字号:大中小 订阅 唯一约束 唯一约束与创建唯一索引基本上是一回事,因为 ...

  9. MySql -- unique唯一约束

    3.UNIQUE 约束 约束唯一标识数据库表中的每条记录. 创建一张测试表 CREATE TABLE `test`.`info`( `id` ) UNSIGNED NOT NULL AUTO_INCR ...

随机推荐

  1. collectionview使用

    创建UICollectionViewFlowLayout 对象来设置相关的布局,包括itemSize,headerReferenceSize,sectionInset.设置对应的布局大小,相关的和顶部 ...

  2. redis中setbit的用法

    原文地址:http://www.zhihu.com/question/27672245 在redis中,存储的字符串都是以二级制的进行存在的.举例:设置一个 key-value ,键的名字叫“andy ...

  3. [手机取证] Jonathan Zdziarski公开的苹果iOS后门及POC视频

    Jonathan Zdziarski 近日在其推特上公布了此“后门”的研究及POC视频,并表示全球媒体“夸大”了此事,自己“从未表示过认为此后门与NSA的监控行为有关”. 视频 http://pan. ...

  4. Wireshark简易教程

    Wireshark是世界上最流行的网络分析工具.这个强大的工具可以捕捉网络中的数据,并为用户提供关于网络和上层协议的各种信息.与很多其他网络工具一样,Wireshark也使用pcap network ...

  5. CRLF和LF

    协作项目,开发环境不同(mac,window)构建过程中,命令行报错(expecting LF but only find CRLF) 打开git bash,输入 $ git config --glo ...

  6. Python-6 分支 循环

    #1 循环 while 条件: 循环体 for 目标 in 表达式: 循环体   表达式可为:range(start,stop,step) break--终止当前循环,并跳出当前循环体. contin ...

  7. os.path 大全

    os.path.abspath(path) #返回绝对路径 os.path.basename(path) #返回一个路径的最后一个组成部分 os.path.commonprefix(list) #返回 ...

  8. core python applications

    第三章: 3.4 电子邮件 SMTP, POP 和 IMAP 协议 第五章: 5.1~5.3 tkinter 各种控件简介 Listbox

  9. 装tomcat和nginx心得

    开机启动tomcat 1:在/etc/rc.d/init.d目录下生成一个文件tomcat8080 2:在文件里添加如下内 #!/bin/bash #2345 linux运行级别 #10开机启动优先级 ...

  10. javaweb 拦截器报错

    拦截器报错   The content of element type "interceptor-ref" must match "(param)*".内容元素 ...