如何使用ASP.NET MVC检查数据库中是否存在重复数据

时间:2018-09-07 12:24:34

标签: c# asp.net asp.net-mvc-4

我想显示一条消息,说明数据库中已经存在JourneyID

模型是:

using System.Web.Mvc;
namespace Project_Final.Models
{
using System;

public partial class sp_FMS_Group6_Module3_ViewBonusMilesRequesttt_Result
{
    public int RequestID { get; set; }
    public Nullable<long> CustomerID { get; set; }
    [Remote("Check", "Home", ErrorMessage = "Bonus Miles Request has already been sent!")]
    public Nullable<int> JourneyID { get; set; }
    public Nullable<System.DateTime> RequestDate { get; set; }
    public string Status { get; set; }
}
}

以下是控制器中的操作:

[HttpPost]
public ActionResult Index(string Create)
{        
        FMS_Group6_Module3_BonusMilesRequestt objProd = new FMS_Group6_Module3_BonusMilesRequestt();
        objProd.CustomerID = int.Parse(Request.Form["CustomerID"].ToString());
        objProd.JourneyID = int.Parse(Request.Form["JourneyID"].ToString());
        objProd.RequestDate = DateTime.Parse(Request.Form["RequestDate"].ToString());
        objProd.Status = "Pending";

        objDB.FMS_Group6_Module3_BonusMilesRequestt.Add(objProd);

        int i = objDB.SaveChanges();
        if (i > 0)
            ViewBag.Message = "Product details saved successfully";
        return Content("<script language='javascript' type='text/javascript'>alert('Your Bonus Miles Request has been successfully sent!');window.location='/Home/GetID'</script>");
        //return Redirect("GetID");
}

public ActionResult Check(string Crreate)
{
        FMS_Group6_Module3_BonusMilesRequestt objProd = new FMS_Group6_Module3_BonusMilesRequestt();
        bool ifJourneyIDExist = false;
        try

        {

            ifJourneyIDExist = Crreate.Equals(objProd.JourneyID) ? true : false;

            return Json(!ifJourneyIDExist, JsonRequestBehavior.AllowGet);

        }

        catch (Exception ex)

        {

            return Json(false, JsonRequestBehavior.AllowGet);

        }
}

任何帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:1)

在插入之前,可以检查数据库是否存在JourneyID

if (objDB.FMS_Group6_Module3_BonusMilesRequestt.Any(x => x.JourneyID == objProd.JourneyID))
{
    // Exists
}

答案 1 :(得分:0)

LINQ查询以确保所有值(不可枚举)都不重复

var noDuplicationVariable = enumerableValues.GroupBy(a => a.Key).All(b => b.Count() == 1);

将其用作函数之前的断言条件