c# - 使用 EntityFramework(数据库优先)方法的 DataAnnotations

标签 c# asp.net entity-framework-4 data-annotations

我有一个项目,其中提供了一个数据库模型类以及一个单独的 EDMX EF 模型。在同一个解决方案中,我有一个 Web 服务可以访问该项目以及模型类。我希望模型类针对前端执行数据注释以进行验证,但根本没有得到验证。

为简洁起见,模型类(在我的模型项目中)如下所示。我的 Web 服务引用此类并用作接口(interface)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ServiceModel;
using System.Runtime.Serialization; 

[DataContract]
[MetadataType(typeof(CustomerMetaData))]
public partial class Customer
{
}

public class CustomerMetaData
{
    [DataMember]
    public object CustomerID { get; set; }

    [Required]
    [StringLength(50)]
    [DataType(DataType.EmailAddress)]
    [DataMember]
    public object Email { get; set; }
}

当我点击表单上的提交按钮时,它会尝试添加记录但不进行任何验证。发生运行时错误,通知我需要电子邮件地址。我显然希望通过数据注释预先完成此验证。

我怎样才能做到这一点?

返回一个实际的运行时错误,指出在尝试添加记录时电子邮件地址不应为 NULL。这是对的。数据库列需要一个值。

我认为通过在模型中添加数据注释,如果前端出现问题并且在尝试发布表单时模型无效,则相应的数据注释错误应该显示在表单上。我的印象是不需要编写任何特定的客户端验证。该模型应该为您处理。我的这个假设不正确吗?

网络上有关于如何使用 CodeFirst 执行此操作的文章,但我没有看到有关如何使用 DataBaseFirst 执行此操作的文章没有。如何做到这一点?

再一次,我的 Customer 类如下。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ServiceModel;
using System.Runtime.Serialization;

namespace YeagerTechModel
{
    [Serializable]
    [DataContract]
    //[MetadataType(typeof(CustomerMetaData))]
    public partial class Customer
    {
        public Customer()
        {
            this.Projects = new HashSet<Project>();
        }

        [DataMember]
        public short CustomerID { get; set; }

        [Required]
        [StringLength(50)]
        [DataType(DataType.EmailAddress)]
        [DataMember]
        public string Email { get; set; }

        [StringLength(50)]
        [DataType(DataType.Text)]
        [DataMember]
        public string Company { get; set; }

        [StringLength(50)]
        [DataType(DataType.Text)]
        [DataMember]
        public string FirstName { get; set; }

        [StringLength(50)]
        [DataType(DataType.Text)]
        [DataMember]
        public string LastName { get; set; }

        [StringLength(50)]
        [DataType(DataType.Text)]
        [DataMember]
        public string Address1 { get; set; }

        [StringLength(50)]
        [DataType(DataType.Text)]
        [DataMember]
        public string Address2 { get; set; }

        [StringLength(50)]
        [DataType(DataType.Text)]
        [DataMember]
        public string City { get; set; }

        [StringLength(2)]
        [DataType(DataType.Text)]
        [DataMember]
        public string State { get; set; }

        [StringLength(10)]
        [DataType(DataType.Text)]
        [RegularExpression(@"^\d{5}(-\d{4})?$")]
        [DataMember]
        public string Zip { get; set; }

        [StringLength(12)]
        [DataType(DataType.PhoneNumber)]
        [DataMember]
        public string HomePhone { get; set; }

        [StringLength(12)]
        [DataType(DataType.PhoneNumber)]
        [DataMember]
        public string CellPhone { get; set; }

        [StringLength(100)]
        [DataType(DataType.Url)]
        [DataMember]
        public string Website { get; set; }

        [StringLength(50)]
        [DataType(DataType.EmailAddress)]
        [DataMember]
        public string IMAddress { get; set; }

        [DataMember]
        public System.DateTime CreatedDate { get; set; }

        [DataMember]
        public Nullable<System.DateTime> UpdatedDate { get; set; }

        public virtual ICollection<Project> Projects { get; set; }
    }
}

当我在客户端调试“if (ModelState.IsValid)”时,该属性始终返回 true。就好像 DataAnnotations 甚至没有被识别。调试时,我检查了 ModelState 对象,它有所有的属性值(在所有情况下都是空字符串,因为我试图强制出错)。我应该在我故意留空的电子邮件地址上收到 isRequired 错误。

[HttpPost]
        public ActionResult Create(YeagerTechWcfService.Customer cust)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    db.AddCustomer(cust);
                    TempData["ErrCode"] = "Customer successfully added.";
                    return RedirectToAction("Index", "Home");
                }
                catch (Exception ex)
                {
                    ViewData["ErrCode"] = "CustErr";
                    ViewBag.Error = ex.Message;
                    return View();
                }
            }
            else
                return View();
        }

最佳答案

不幸的是,这个注解似乎只影响渲染,不影响验证。我刚刚遇到了与 DataType.Url 相同的问题,它也在问题 Is the DataTypeAttribute validation working in MVC2? 中进行了讨论。 (尽管对于 MVC 2 - 但问题在 3 中似乎是一样的)。

只需在其上放置一个正则表达式数据注释:

[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Email was invalid.")]

关于c# - 使用 EntityFramework(数据库优先)方法的 DataAnnotations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7166521/

相关文章:

c# - 列 ID 在规范中出现多次

c# - 从 Windows 服务访问数据库

c# - 找不到 JobRunShell.cs

c# - 两个函数之间耗时

asp.net - 我是 .NET Core 2.1 MVC 的新手,无法理解一些事情的工作原理

c# - 如何解决 'Could not load file or assembly ' Microsoft.AI.Web' 或其依赖项之一的错误?

c# - jQuery/ajax POST 一个数组/对象到后面的 C# 代码

wcf - EF4 自跟踪实体和 WCF 序列化导致堆栈溢出

c# - 业务对象和业务逻辑有什么区别

c# - 从另一个函数调用 HTTP 触发的 Azure 函数