Validate a unique input field from a foreign key

211 views Asked by At

i have a table rubriqueintermediare with two fields rubriqueId and rubriqueintermediareId which is a foreign key from the table Rubrique.

My table Rubriqueintermediare have a listbox of the libelle field from the rubrique table.

When I add a new rubriqueintermediare I mustn't add an existing one in the rubriqueintermediare list.

How could I do this validation when I have just rubriqueintermediareId and rubriqueId in the table rubriqueintermediare which are auto incremented in my sql server. ther is my methode add in the controller of rubriqueintermediare:

[HttpPost]
    public JsonResult Save([DataSourceRequest] DataSourceRequest dsRequest, RubriqueIntermediareVM vm)
    {
        try
        {
            ViewData["CodeRubrique"] = new SelectList(RefDataManager.GetRefData<RubriqueVM>(), "RubriqueId", "CODELIBELLE");
            if (ModelState.IsValid)
            {
                RubriqueIntermediareVM rubi = ServiceApplicatif.Save(vm);
                IEnumerable<RubriqueVM> rubrique = RefDataManager.GetRefData<RubriqueVM>() as IEnumerable<RubriqueVM>;
            }
            DataCache dataCache = new DataCache(CurrentSecurityContext.TenantID);
            dataCache.DropDataCache<RubriqueIntermediareVM>();
            return Json(new[] { vm }.ToDataSourceResult(dsRequest, ModelState));
        }
        catch (Exception ex)
        {
            LoggerRubriqueIntermediare.Error(string.Format("Exception : {0}", ex.Message.ToString()));
            throw new Exception("Erreur lors de l'enregistrement.");
        }
    }
1

There are 1 answers

1
Rudra Sisodia On

You have to do this validation into your database

In store procedure

if exists( select Count(id) 
           from Rubriqueintermediare 
           where @name=rubricname) -- Assuming rubricname is column  
begin
    --return field as you want 
END
Else
Begin
    --Insert as you want
End