anouar
anouar

Reputation: 317

How to check that the ID is not duplicated in ASP MVC and EF

I am developing an ASP .Net MVC 3application using C# and SQL Server 2005.

I am using also Entity Framework and Code First Method.

I have a model Poste related to a table Poste in my base.

When I want to add a new poste, I would like that its ID 'Primary Key' will be checked in order to not be duplicate and produice an Exception.

I try to use Remote but there is some problems.

This is what I try :

Model :

public class Poste
    {
        [Required]
        [Key]
        [Display(Name = "ID Poste :")]
        [Remote("PosteExists", "Poste", "ID is already taken.")]
        public string ID_Poste { get; set; }

In the Controller 'PosteController' :

public JsonResult PosteExists(string poste)
        {
            var p = _repository.GetPosteByName(poste.Trim());
            return p == null ?
                Json(true, JsonRequestBehavior.AllowGet) :
                Json(string.Format("{0} is not available.", poste),
                    JsonRequestBehavior.AllowGet);
        }

First, _repository does not exist in the current Context.

Second, I don't is this solution will be check the values from the base.

Upvotes: 2

Views: 1095

Answers (3)

Adam Tuliper
Adam Tuliper

Reputation: 30152

The remote attribute will work fine. Where did you get your _repository code from? Why can't you create an instance in your controller?

Also be aware that the Remote attribute doesn't validate when you post the form back to the action method, you will need to validate it again on the server side.

Upvotes: 0

Colm Prunty
Colm Prunty

Reputation: 1620

You have db access in that controller, so you can check against that.

public JsonResult PosteExists(string poste)
{
    var exists = db.Postes.Any(x => x.ID_Poste == poste.Trim())
    return !exists ?
        Json(true, JsonRequestBehavior.AllowGet) :
        Json(string.Format("{0} is not available.", poste),
        JsonRequestBehavior.AllowGet);
}

Assuming ID_Poste is what you're checking against.

Upvotes: 0

emre nevayeshirazi
emre nevayeshirazi

Reputation: 19241

You do not need to check whether it is used or not. Just define a primary key of type integer and it will be auto incremented in database for each record inserted.

public int PosteID { get; set; }

By convention PosteID will become the primary key of table Poste.

Upvotes: 1

Related Questions