使用Entity Framework创建数据库索引 [英] Create database index with Entity Framework

查看:113
本文介绍了使用Entity Framework创建数据库索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下模式:

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

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

[必需]
[StringLength(15)]
public string IMEI {get;组; }
}

是否可以向 IMEI 列通过使用属性,数据注释或模型中的某些东西?

解决方案

根据此链接:通过实体框架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;私人集合}

public bool IsUnique {get;私人集合
}

而第二类:

 使用System.ComponentModel.DataAnnotations.Schema; 
使用System.Data.Entity;
使用System.Linq;
使用System.Reflection;

public class IndexInitializer< T> :IDatabaseInitializer< T>其中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&
{
var entityType = dataSetProperty.PropertyType.GetGenericArguments()。Single();

TableAttribute [] tableAttributes =(TableAttribute [])entityType.GetCustomAttributes(typeof(TableAttribute),false);

foreach(entityType.GetProperties(PublicInstance)中的var属性)
{
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) ,假);

foreach(indexAttributes中的var indexAttribute)
{
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);
}
}
}
}
}
}

之后,您可以使用索引

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


Say I have the following model:

[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; }
}

Is it possible to add an index to the IMEI column through using an attribute, data annotation, or something from the model?

解决方案

According to this link: Creating Indexes via Data Annotations with Entity Framework 5.0 you should write some kind of extension code:

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; }
}

and the second class:

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);
                    }
                }
            }
        }
    }
}

After it you can use your index this way:

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

这篇关于使用Entity Framework创建数据库索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆