c# - 使用 Entity Framework 创建数据库索引

标签 c# .net entity-framework indexing data-annotations

假设我有以下模型:

[Table("Record")]
public class RecordModel
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    [Display(Name = "Record Id")]
    public int RecordId { get; set; }

    [StringLength(150)]
    public string Name { get; set; }

    [Required]
    [StringLength(15)]
    public string IMEI { get; set; }
}

是否可以向 IMEI 添加索引?通过使用属性、数据注释或模型中的东西来列?

最佳答案

根据此链接: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; }

关于c# - 使用 Entity Framework 创建数据库索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16853909/

相关文章:

c# - 结构的不变性

c# - Compact Framework 2.0 - 表单与将控件加载到面板中

c# - 提交时索引超出范围(Fluent NHibernate)

c# - WPF:加载 XAML 文件,其中包含 x:Code 元素

entity-framework - 使用Moq和Autofac在单元测试中 Entity Framework 的扩展方法

.net - 存储过程在 Entity Framework 中很慢

c# - .aspx 文件中的 JavaScript 中的 "Expected expression"和 <%=foo%>

.net - 使用WPF的ShowDialog打开表单时发生异常

c# - 上传文件到数据库

c# - Entity Framework Sqlite 数据库 : NotSupportedException