MVC实体框架验证以防止重复记录 [英] MVC Entity Framework validation to prevent duplicate records

查看:82
本文介绍了MVC实体框架验证以防止重复记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我是MVC和EF的新手,所以这可能是一个非常简单的问题,但是最好的方法是阻止用户尝试输入重复记录?



我有一个简单的查询表,其中一列是主键。我正在创建维护屏幕,以便管理员可以向查找列表添加额外的项目。我的控制器看起来像:

  public ActionResult索引(string NewRow)
{
try
{
CaseType t = new CaseType {ID = NewRow};
if(ModelState.IsValid)
{
UOW.CaseTypes.Add(t);
UOW.Save();
}
}
catch(Exception ex)
{
ModelState.AddModelError(,ex.Message);
}
return View(UOW.CaseTypes.All());
}

哪些停止重复记录并停止黄色屏幕死亡,但显示消息is:更新条目时发生错误,有关详细信息,请参阅内部异常。这对用户来说是不好的。



我只是想知道是否有更好的方法来捕捉错误。

解决方案

对于显示验证错误,我使用这样的东西:



MainEmail是ViewModel的属性

  var mod = ModelState.First(c => c.Key ==MainEmail); // this 
mod.Value.Errors.Add(Row's should do duplicates。); // this

if(ModelState.IsValid)
{
return RedirectToAction(Details);
}

return View(client);

视图中会显示此字段中的错误:

 < div class =editor-label> 
@ Html.LabelFor(model => model.MainEmail)
< / div>

未来,您必须隐藏您的错误屏幕!您需要显示一个自定义错误页面:



如果使用asp-mvc-3,请添加到web.config这样的字符串:

 < system.web> 
< customErrors mode =OndefaultRedirect =〜/ Error/>
...

用户将拥有/Shared/Error.cshtml页面有例外消息(可以显示sequrity数据)。



添加



这里讨论了唯一约束创建
实体框架中的唯一约束代码首先



比您可以检查与您的尝试代码的记录重复。



在我的应用程序中,我使用并且不添加唯一约束,因为它导致低可测试性。在这种情况下,请在保存更改之前使用简单的查找



第一个aproach快一点。



方法二是成长可测试性。


Hi i'm new to MVC and EF so this may be a really simple question but what is the best way to prevent the user from trying to enter duplicate records?

I have a simple look up table with one column which is the primary key. I'm creating a maintenance screen so admins can add extra items to the look up list. My controller looks like :

public ActionResult Index(string NewRow)
    {
        try
        {
            CaseType t = new CaseType { ID = NewRow };
            if (ModelState.IsValid)
            {
                UOW.CaseTypes.Add(t);
                UOW.Save();
            }
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("", ex.Message);
        }
        return View(UOW.CaseTypes.All());
    }

Which stops the duplicate records and stops the yellow screen of death but the message displayed is : "An error occurred while updating the entries. See the inner exception for details." which is no good for the users.

I was just wondering if there is a better way to catch the error.

解决方案

For show validation error I use something like this:

MainEmail it's property from ViewModel

        var mod = ModelState.First(c => c.Key == "MainEmail");  // this
        mod.Value.Errors.Add("Row's shouldn't duplicates.");    // this

        if (ModelState.IsValid)
        {
            return RedirectToAction("Details");
        }

        return View(client);

Error will show's in this field in view:

    <div class="editor-label">
        @Html.LabelFor(model => model.MainEmail)
    </div>

And for future, you must hide your error screen! You need to display a custom error page:

If you use asp-mvc-3, add to web.config such string:

  <system.web>
     <customErrors mode="On" defaultRedirect="~/Error" />
     ...

And users will have /Shared/Error.cshtml page insted of page with exception message (which can show sequrity data).

ADD

About unique constraint creation was discussed here Unique Constraint in Entity Framework Code First

than you can check about records duplication with your try code.

In my application I use code first and don't add unique constraint because it's lead to low testability. In that case use simple Find before saving changes.

First aproach is little bit faster.

Approach two is grow up testability.

这篇关于MVC实体框架验证以防止重复记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆