如何在 Entity Framework Code First 中使属性唯一

这是我的User模型类:


public class User 

{

    public int Id { get; set; }


    [Required]

    [MaxLength(100)]

    public string FullName { get; set; }


    [Required]

    [MaxLength(30)]

    [Remote("IsUsernameExists", "Home", HttpMethod = "Post")]

    public string UserName { get; set; }


    [Required]

    [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$"]

    public string Email { get; set; }


    [Required]

    [StringLength(maximumLength: 18, MinimumLength = 8)]

    public string Password { get; set; }

}

这是控制器中的IsUsernameExists方法Home


public JsonResult IsUsernameExists(string UserName)

{            

    return Json(!db.Users.Any(x => x.Username == UserName), JsonRequestBehavior.AllowGet);

}

但它不起作用。任何进一步的帮助将不胜感激!


侃侃尔雅
浏览 103回答 3
3回答

开满天机

您可以Unique使用 Both来创建模型属性DataAnnotation,FluentApi如下所示:使用数据注释:[Required][StringLength(30)][Index("Ix_UserName",Order =1,IsUnique =true)]public string UserName { get; set; }使用流畅的 API:在实体框架 >= 6.2 中,在DbContext:protected override void OnModelCreating(DbModelBuilder modelBuilder){&nbsp; &nbsp; &nbsp;base.OnModelCreating(modelBuilder);&nbsp; &nbsp; &nbsp;modelBuilder.Entity<User>().Property(u => u.UserName).HasMaxLength(30);&nbsp; &nbsp; &nbsp;modelBuilder.Entity<User>().HasIndex(u => u.UserName).IsUnique();}在实体框架 < 6.2在DbContext:protected override void OnModelCreating(DbModelBuilder modelBuilder){&nbsp; &nbsp; &nbsp;base.OnModelCreating(modelBuilder);&nbsp; &nbsp; &nbsp;modelBuilder.Entity<User>().Property(t => t.UserName).HasMaxLength(30)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("Ix_UserName"){IsUnique = true}));}请记住:对于Index属性,您还必须使用StringLength属性。为了使工作,请按如下方式RemoteAttibute写下您 RemoteAttibute的财产:UserName[Required][StringLength(30)][Index("Ix_UserName",Order =1,IsUnique =true)][Remote("IsUserNameExist", "Home", AdditionalFields = "Id", ErrorMessage = "User Name already exists")]public string UserName { get; set; }然后IsUserNameExist方法HomeController如下:public JsonResult IsUserNameExist(string UserName, int? Id){&nbsp; &nbsp; &nbsp;var IsUserNameExists = db.Users.Any(x => x.UserName== UserName && x.Id != Id);&nbsp; &nbsp; &nbsp;return Json(!IsUserNameExists, JsonRequestBehavior.AllowGet);}最后确保您的视图包含以下jQuery文件:<script src="~/Scripts/jquery-version.min.js"></script><script src="~/Scripts/jquery.validate.min.js"></script><script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

慕工程0101907

RemoteAttribute与实体框架没有任何关系。它只是忽略了这个属性。此外,正如文档所说,它是一个jQuery验证属性,它应该只在前端部分起作用。如果User同时是 MVC 模型和数据库实体,则应为属性创建唯一索引。一种方法是OnModelCreating在你的方法中DbContext:protected override void OnModelCreating(ModelBuilder modelBuilder){&nbsp; &nbsp; modelBuilder.Entity<User>().HasIndex(x => new { x.Username }).IsUnique();}然后创建一个迁移,将它应用到数据库,你就可以开始了。但是,请注意保存副本时会遇到的异常,并确保正确处理它。

长风秋雁

我在 HomeController 中创建了一个方法&nbsp; &nbsp;public bool IsUserExist(string email)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; return db.Users.Where(c => c.Email == email).IsAny();&nbsp; &nbsp;}&nbsp;并在行动&nbsp; &nbsp; if( IsUserExist(model.Email) )&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // my code&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP