我这样做。我想检查用户名是否已插入数据库中。
Mst_Users obj = new Mst_Users();
obj.UserName = txtUserName.Text;
obj.ContactNo = txt_ContactNo.Text.Trim();
obj.Address = txt_Address.Text;
obj.CreatedBy = LoginHandler.UserData.UserId;
obj.CreatedOn = DateTime.Now;
obj.IsActive = true;
obj.PasswordHash = Password;
obj.RoleId = Convert.ToInt32(chkRoles.SelectedValue);
obj.OtherDetails = txt_OtherDetails.Text;
objEntity.Mst_Users.Add(obj);
int result = objEntity.SaveChanges();
if (result > 0)
{
MessageBox("Record Added Succesfully");
txtUserName.Text = string.Empty;
txt_ContactNo.Text = string.Empty;
txt_Address.Text = string.Empty;
txt_OtherDetails.Text = string.Empty;
chkRoles.ClearSelection();
}
答案 0 :(得分:0)
首先,您需要检查是否存在具有此用户名的用户,您需要在使用任何添加/保存代码之前执行此操作。
典型地,它有点像这样
var user = yourDbContext.Where(u=>u.UserName == "UserNameYouWantToCheck").FirstOrDefault();
if(user!=null)
throw new ArgumentException(); //or do whatever you want to do when an user like this exists
//code for adding your user to the application db context and for saving the data.
至于依赖的验证方法,如果您正在进行MvC项目,那么您可以使用ModelState,您可以检查模型是否有效并从中访问验证消息。但如果你正在做一些你刚刚从github添加EF的项目,那么你可以使用Validator,这是一个例子:
public static bool IsValid(object model)
{
var context = new ValidationContext(model, null, null);
var results = new List<ValidationResult>();
if (Validator.TryValidateObject(model, context, results, true))
{
return true;
}
return false;
}
然后您只需将要检查的模型类型对象传递给此IsValid方法,并且可以在结果列表中检查验证消息
普罗蒂普。在开始学习EF
之前,请先阅读linq