ایجاد ایندکس منحصربفرد در EF Code first
نویسنده: وحید نصیری
تاریخ: ۱۳۹۱/۰۶/۱۴ ۲۲:۱۳
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public static void CreateUniqueIndex(this DbContext context, string tableName, string fieldName)
{
context.Database.ExecuteSqlCommand("CREATE UNIQUE INDEX [IX_Unique_" + tableName
+ "_" + fieldName + "] ON [" + tableName + "]([" + fieldName + "] ASC);");
}
public class MyDbMigrationsConfiguration : DbMigrationsConfiguration<MyContext>
{
public BlogDbMigrationsConfiguration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(MyContext context)
{
CreateUniqueIndex(context, "table1", "field1");
base.Seed(context);
}
}
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
namespace General
{
public static class ContextExtensions
{
public static string GetTableName<T>(this DbContext context) where T : class
{
ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
return objectContext.GetTableName<T>();
}
public static string GetTableName<T>(this ObjectContext context) where T : class
{
var sql = context.CreateObjectSet<T>().ToTraceString();
var regex = new Regex("FROM (?<table>.*) AS");
var match = regex.Match(sql);
string table = match.Groups["table"].Value;
return table
.Replace("`", string.Empty)
.Replace("[", string.Empty)
.Replace("]", string.Empty)
.Replace("dbo.", string.Empty)
.Trim();
}
private static bool hasUniqueIndex(this DbContext context, string tableName, string indexName)
{
var sql = "SELECT count(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS where table_name = '"
+ tableName + "' and CONSTRAINT_NAME = '" + indexName + "'";
var result = context.Database.SqlQuery<int>(sql).FirstOrDefault();
return result > 0;
}
private static void createUniqueIndex(this DbContext context, string tableName, string fieldName)
{
var indexName = "IX_Unique_" + tableName + "_" + fieldName;
if (hasUniqueIndex(context, tableName, indexName))
return;
var sql = "ALTER TABLE [" + tableName + "] ADD CONSTRAINT [" + indexName + "] UNIQUE ([" + fieldName + "])";
context.Database.ExecuteSqlCommand(sql);
}
public static void CreateUniqueIndex<TEntity>(this DbContext context, Expression<Func<TEntity, object>> fieldName) where TEntity : class
{
var field = ((MemberExpression)fieldName.Body).Member.Name;
createUniqueIndex(context, context.GetTableName<TEntity>(), field);
}
}
}
context.CreateUniqueIndex<User>(x=>x.Name);
public class MyContext: DbContext
{
public DbSet<Person> People { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().Property(p => p.Name).HasMaxLength(100);
modelBuilder.Entity<Person>().HasIndex(p => p.Name).IsUnique();
}
}