MVC控制器:在保存之前使用LINQ检查表中是否存在重复值?

时间:2015-02-18 22:09:58

标签: c# asp.net-mvc linq asp.net-mvc-5

我的Create() - POST实体有以下Manufacturers控制器:

// POST: INV_Manufacturers/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,manufacturer_description,created_date,created_by,modified_date,modified_by")] INV_Manufacturers iNV_Manufacturers)
{

    iNV_Manufacturers.created_date = DateTime.Now;
    iNV_Manufacturers.created_by = System.Environment.UserName;

    if (ModelState.IsValid == false && iNV_Manufacturers.Id == 0)
    {
        ModelState.Clear();
    }

    if (ModelState.IsValid)
    {
        db.INV_Manufacturers.Add(iNV_Manufacturers);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    return View(iNV_Manufacturers);
}

Model因此被定义:

public class INV_Manufacturers
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Please enter a Manufacturer.")]
    public string manufacturer_description { get; set; }

    [Required]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime created_date { get; set; }

    [Required]
    public string created_by { get; set; }

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime? modified_date { get; set; }

    public string modified_by { get; set; }
}

在我的控制器中使用LINQ的语法是什么,我可以搜索INV_Manufacturers表并检查表中是否已存在Manufacturer description与我将Create()方法中要保存的值进行比较?

伪代码

if (manufacturer.description == ANY.manufacturer.description in Table)
{
    alert("This value already exists in table!");
} else {
    Save(new manufacturer);
}

1 个答案:

答案 0 :(得分:3)

当然,只需使用.Any()即可。它将返回一个布尔值,具体取决于是否找到了实体。在找到它的第一个实例时,它将停止枚举,因此如果它存在,它将快速突破。如果它不存在,它将检查整个表,并返回false(这就是Add!.Any()中的原因)

if(!db.INV_Manufacturers.Any(m => m.manufacturer_description == iNV_Manufacturers.manufacturer_description))
{
    db.INV_Manufacturers.Add(iNV_Manufacturers);
}
else
{
    //logic for when that description exists
    //for example, to add to ModelState
    ModelState.AddModelError("manufacturer_description","Description Exists");
}