【问题标题】:Unique Index using Data Annotations [duplicate]使用数据注释的唯一索引 [重复]
【发布时间】:2013-09-26 09:10:35
【问题描述】:

有没有办法使用数据注释定义唯一索引?

假设我有一门课:

public class User 
{
   [Key]
   public int UserID { get; set; }
   public string UserName { get; set; }
   public string Email { get; set; }
}

如果我希望电子邮件是唯一的,我该如何为其添加唯一索引?

【问题讨论】:

    标签: c# entity-framework ef-code-first indexing data-annotations


    【解决方案1】:

    这与我已经回答过MVC Model - create db index的问题差不多

    根据此链接:Creating Indexes via Data Annotations with Entity Framework 5.0 你应该写一些扩展代码:

    using System; 
    
    [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
    public class IndexAttribute : Attribute
    {
        public IndexAttribute(string name, bool unique = false)
        {
            this.Name = name;
            this.IsUnique = unique;
        }
    
        public string Name { get; private set; }
    
        public bool IsUnique { get; private set; }
    }
    

    第二类:

    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity;
    using System.Linq;
    using System.Reflection;
    
    public class IndexInitializer<T> : IDatabaseInitializer<T> where T : DbContext
    {
        private const string CreateIndexQueryTemplate = "CREATE {unique} INDEX {indexName} ON {tableName} ({columnName})";
    
        public void InitializeDatabase(T context)
        {
            const BindingFlags PublicInstance = BindingFlags.Public | BindingFlags.Instance;
    
            foreach (var dataSetProperty in typeof(T).GetProperties(PublicInstance).Where(
                p => p.PropertyType.Name == typeof(DbSet<>).Name))
            {
                var entityType = dataSetProperty.PropertyType.GetGenericArguments().Single();
    
                TableAttribute[] tableAttributes = (TableAttribute[])entityType.GetCustomAttributes(typeof(TableAttribute), false);
    
                foreach (var property in entityType.GetProperties(PublicInstance))
                {
                    IndexAttribute[] indexAttributes = (IndexAttribute[])property.GetCustomAttributes(typeof(IndexAttribute), false);
                    NotMappedAttribute[] notMappedAttributes = (NotMappedAttribute[])property.GetCustomAttributes(typeof(NotMappedAttribute), false);
                    if (indexAttributes.Length > 0 && notMappedAttributes.Length == 0)
                    {
                        ColumnAttribute[] columnAttributes = (ColumnAttribute[])property.GetCustomAttributes(typeof(ColumnAttribute), false);
    
                        foreach (var indexAttribute in indexAttributes)
                        {
                            string indexName = indexAttribute.Name;
                            string tableName = tableAttributes.Length != 0 ? tableAttributes[0].Name : dataSetProperty.Name;
                            string columnName = columnAttributes.Length != 0 ? columnAttributes[0].Name : property.Name;
                            string query = CreateIndexQueryTemplate.Replace("{indexName}", indexName)
                                .Replace("{tableName}", tableName)
                                .Replace("{columnName}", columnName)
                                .Replace("{unique}", indexAttribute.IsUnique ? "UNIQUE" : string.Empty);
    
                            context.Database.CreateIfNotExists();
    
                            context.Database.ExecuteSqlCommand(query);
                        }
                    }
                }
            }
        }
    }
    

    之后你可以这样使用你的index:

    [Required]
    [Index("IMEIIndex", unique: true)]
    [StringLength(15)]
    public string IMEI { get; set; }
    

    【讨论】:

    • 您应该将此问题标记为重复,而不是重复答案。
    • @GertArnold - 完成 - 标记
    • 谢谢。但我认为你也应该删除这个答案。冗余内容是一个问题,因为内容可以一直被编辑(= 改进)。如果您对代表感兴趣(谁不感兴趣?),那么当被重定向到另一个答案时,觉得这个答案有帮助的人可能会赞成另一个答案。并且有各种闪亮的徽章可以赚取高票的答案! - 好吧,只是一个评论。两个好的答案仍然比一个差的答案好:)
    • @GertArnold - 我不确定它是否 100% 是同一个问题 - 这就是我重新发布答案的原因
    • @GertArnold - 我也不知道为什么版主没有反应将其标记为重复。我已经标记了它。也许您也可以将其标记为重复 - 然后版主会做出反应 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多