zoukankan      html  css  js  c++  java
  • 如何在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;
        }
    }
    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 扩展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)");
      }
    }
    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());
    View Code



    参考文献:http://stackoverflow.com/questions/5701608/unique-key-with-ef-code-first
     
  • 相关阅读:
    疑问
    Android之Adapter用法总结-(转)
    Android之Adapter用法总结(转)
    ListView中每个item条目在被单击选中时能够高亮显示
    使用简单的python语句编写爬虫 定时拿取信息并存入txt
    Python实现简单的爬虫获取某刀网的更新数据
    scrapy-redis(七):部署scrapy
    Scrapy-redis改造scrapy实现分布式多进程爬取
    Scrapy-redis实现分布式爬取的过程与原理
    https://blog.csdn.net/u012150179/article/details/38091411
  • 原文地址:https://www.cnblogs.com/ShadowLoki/p/3310419.html
Copyright © 2011-2022 走看看