MVC controller: using LINQ to check for a duplicate value that already exists in the table before saving?

I have the following Create() - POSTcontroller for my object 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 defined in this way:

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

What is the syntax using LINQin my controller where I can search the table INV_Manufacturersand check if the table exists Manufacturerwith the same descriptioncompared to the value that is stored in my method Create()?

PSEUDOKOD

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

, .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");
}
+3

All Articles