【问题标题】:MVC Controller: Using LINQ to check for duplicate value already existing in table before Save?MVC 控制器:在保存之前使用 LINQ 检查表中是否存在重复值?
【发布时间】:2015-04-20 02:54:34
【问题描述】:

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

// 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 表并检查表中是否已经存在具有相同descriptionManufacturer保存在我的Create() 方法中?

伪码

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

【问题讨论】:

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


【解决方案1】:

当然,只需使用.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");
}

【讨论】:

  • 谢谢特拉维斯!关于(当描述存在时)将此类消息发回视图的任何提示?
  • @AnalyticLunatic 这取决于此代码所在的位置。有很多方法可以完成这项任务。您可以将它放在 ModelState 字典中并使描述无效,迫使用户更改它,您可以简单地声明有错误,您可以将详细的错误消息作为视图模型的一部分发回,您可以先使用 ajax 进行测试在提交之前的视图中,然后以这种方式提供信息,您可以使用 TempData 放置一个指示错误的字符串并在视图中查找 TempData,可能还有更多选项。选择在你的应用范围内有意义的东西:)
  • 嗯...好吧,我在我的控制器中。您是否有放入ModelState - dictionary 并使描述无效的示例?这听起来像是一条有趣的尝试路线。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
  • 2018-03-31
  • 2017-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多