唯一键约束验证MVC 4 (Fluent API)

本文关键字:Fluent API MVC 一键 约束 验证 唯一 | 更新日期: 2023-09-27 18:09:00

我的项目分为控制器、模型、服务、参数和视图。
我不用EF。我尝试使用此代码验证唯一键约束,但对于EF。

public static ValidationResult IsUserNameUnique(object username, ValidationContext context)
{
            ADMINEntities x = new ADMINEntities();
            var users = from u in x.Users
                        select u;
            foreach (var item in users)
            {
                if (item.Username == username.ToString())
                {
                    return new ValidationResult("Username is already choosen, please choose another one.");
                }
            }
            return ValidationResult.Success;
}

我如何改变代码,以适应流利?
No have edmx.
No have Context.

唯一键约束验证MVC 4 (Fluent API)

我假设您想要删除foreach循环并拥有更简洁的代码。可以使用FirstOrDefault扩展编写一个等效但更短的查询:

var x = new ADMINEntities();
var usersExists = x.Users.FirstOrDefault(u => u.Username == username.ToString());
return usersExists != null
            ? new ValidationResult("Username is already choosen, please choose another one.")
            : ValidationResult.Success;