如何在EF CodeFirst中使用唯一约束(Unique)
一直用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(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; } }
方式2 扩展DataBase
SetInitializer 使用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()[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 + ")"); } } } } } } }
在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
posted on 2013-09-09 18:52 Manon_Loki 阅读(10837) 评论(2) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!