分享

如何在EF CodeFirst中使用唯一约束(Unique)

 蜗牛之窝 2014-05-13

一直用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;
    }
}

复制代码


 


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

复制代码


 




方式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)");
  }
}

复制代码


 



在DbContext中使用



Database.SetInitializer<MyContext>(new MyInitializer());



 




方式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 + ")");
                                }
                            }
                        }
                    }
                }
            }
        }

复制代码



在DbContext中使用



System.Data.Entity.Database.SetInitializer<MyApp.Models.DomainModels.myEntities>(new MyApp.Models.DomainModels.myEntities.Initializer());



 





参考文献:http:///questions/5701608/unique-key-with-ef-code-first

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多