简体   繁体   English

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

[英]DataAnnotations with EntityFramework (Database First) method

I have a project in which I have a database model class provided along with a separate EDMX EF model. 我有一个项目,其中提供了一个数据库模型类以及一个单独的EDMX EF模型。 In the same solution, I have a web service which accesses this project along with the model class. 在同一个解决方案中,我有一个Web服务,它与模型类一起访问该项目。 I want the model class to perform data annotations against the front end for validation, but is not getting validated at all. 我希望模型类针对前端执行数据注释以进行验证,但是根本没有得到验证。

For brevity, the model class (in my Model project) is as follows. 为简洁起见,模型类(在我的Model项目中)如下所示。 My web service references this class and is used as the interface. 我的Web服务引用此类并用作接口。

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

When I hit the Submit button on the form, it tries to add the record and does not do any validation. 当我点击表单上的“提交”按钮时,它会尝试添加记录,但不会进行任何验证。 A runtime error occurs informing me that the email address is required. 发生运行时错误,通知我需要电子邮件地址。 I obviously want this validation to be done up front with the data annotations. 我显然希望使用数据注释预先完成此验证。

How can I accomplish this? 我怎么能做到这一点?

An actual runtime error is coming back saying that the email address should not be NULL when the record tries to be added. 实际的运行时错误回来说当尝试添加记录时,电子邮件地址不应为NULL。 This is correct. 这是对的。 The database column requires a value. 数据库列需要一个值。

I thought that by having the data annotations in the model, if there is something wrong with the front end and the model is not valid once the form tries to be posted, the corresponding data annotation error should display on the form. 我认为通过在模型中使用数据注释,如果前端出现问题并且一旦表单尝试发布时模型无效,则相应的数据注释错误应显示在表单上。 I was under the impression that there is no need for writing any specific client side validation. 我的印象是没有必要编写任何特定的客户端验证。 The model is supposed to take care of that for you. 该模型应该为您照顾。 Am I incorrect in this assumption? 这个假设我不正确吗?

There are articles on the web how to do this with CodeFirst , but I have seen none on how to do this with DataBaseFirst . 有网络如何与CodeFirst做到这一点的文章,但我已经看到了没有就如何处理DataBaseFirst做到这一点。 How can this be accomplished? 如何实现这一目标?

Once again, my Customer class is as follows. 我的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; }
    }
}

When I debug the "if (ModelState.IsValid)" in my client, the property always returns true. 当我在客户端调试“if(ModelState.IsValid)”时,该属性始终返回true。 It's as if the DataAnnotations are not even being recognized. 就好像DataAnnotations甚至没有被识别一样。 When debugging, I check the ModelState object and it has all the property values there (an empty string in all cases since I'm trying to force an error). 在调试时,我检查了ModelState对象,并且它具有所有属性值(在所有情况下都是空字符串,因为我试图强制发生错误)。 I should be getting an isRequired error on the email address which I'm purposely leaving blank. 我应该在电子邮件地址上收到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();
        }

Unfortunately this annotation only appears to affect rendering, not validation. 不幸的是,这个注释只会影响渲染,而不会影响验证。 I've just had the same problem with DataType.Url and it's also discussed in the question Is the DataTypeAttribute validation working in MVC2? 我刚刚遇到了与DataType.Url相同的问题,并且在问题中还讨论了DataTypeAttribute验证是否在MVC2中工作? (albeit for MVC 2 - but the problems seems the same in 3). (虽然对于MVC 2 - 但问题在3中似乎相同)。

Just drop a regular expression data annotation on it: 只需在其上删除正则表达式数据注释:

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

Just to expand on this a bit, in MVC 3 you could go another route to use the validation. 只是为了扩展这一点,在MVC 3中你可以使用另一条路径来使用验证。 I use MVC 3 + EF database first and I can use code like this in the extension/partial Model class: 我首先使用MVC 3 + EF数据库,我可以在扩展/部分Model类中使用这样的代码:

[MetadataType(typeof(Foobar.Metadata))]
[Serializable]
public partial class Foobar
{
    private sealed class Metadata
    {
        [Required]
        [MinLength(10)]
        public object Name { get; set; }
    }

    // Other stuff here
}

Then when I can feed my little Foobar an invalid name in a controller action and I can get the validation errors nicely by using TryValidateModel instead of ModelState.IsValid (Horror of horrors, I don't databind). 然后,当我可以在控制器动作中为我的小Foobar提供一个无效的名称时,我可以通过使用TryValidateModel而不是ModelState.IsValid(恐怖的恐怖,我没有数据绑定)很好地得到验证错误。

        Foobar c = new Foobar();
        c.Name = "ponies";

        var y = TryValidateModel(c);
        if (!y)
        {
            foreach (var item in ModelState.Values)
            {
                foreach (var err in item.Errors)
                {
                    DoxLog.Error(err.ErrorMessage, err.Exception);
                }
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 EntityFramework和DataAnnotations,未显示错误 - EntityFramework and DataAnnotations, errors not showing 代码首先使用EntityFramework 4链接到数据库 - Code first linking to database with EntityFramework 4 有没有一种方法可以在Silverlight中编译实体框架数据注释? - Is there a way to compile entityframework dataannotations in silverlight? 使用数据库优先方法将DataAnnotations添加到实体类 - Add DataAnnotations to entity class using database first approach EntityFramework首先使用数据库检测复杂类型 - EntityFramework detecting complex type with database first EntityFramework 6.0 CreateDatabaseIfNotExists代码首先创建数据库 - EntityFramework 6.0 CreateDatabaseIfNotExists Code first to create database EntityFramework.BulkInsert不适用于数据库优先 - EntityFramework.BulkInsert not working for database-first C#将DataAnnotations添加到EntityFramework中的实体 - C# adding DataAnnotations to entities from the EntityFramework EntityFramework中带有DataAnnotations的联结表中的额外字段 - Extra field in junction table with DataAnnotations in EntityFramework 从数据库更新模型时出错(EntityFramework数据库优先) - Error in Updating the model from database (EntityFramework Database-First)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM