Mohit
Mohit

Reputation: 151

How to check if a value already exists in my database and show a validation message in ASP.NET & Entity Framework

I am doing this. I want to check if the username is already inserted in database or not.

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();
}

Upvotes: 0

Views: 4082

Answers (1)

XomRng
XomRng

Reputation: 171

First you need to check if a user with this username exists, you need to do this before you use any adding/saving code.

typicaly its done somewhat like this

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.

As for validation method that depends, if you are doing MvC project then you can use ModelState, you can check if model is valid and access validation messages from it. but if you are doing some other project to which you just added EF from github then you could use Validator, here is an example:

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

then you just pass your model type object you want to check as parameer to this IsValid method and you can check your validation messages in the results list

Protip. Read about linq before you start learning about EF

Upvotes: 1

Related Questions