使用实体框架数据模型添加验证属性 [英] Adding Validation Attributes With an Entity Framework Data Model

查看:40
本文介绍了使用实体框架数据模型添加验证属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

2015 年 2 月前言如果您仍在使用 Entity Framework EDMX,请帮自己一个忙并使用 Entity Framework Code First 进行检查.不同之处在于您的表是从您的模型类创建的,而不是在 EDMX 中,您的模型类是用您的表创建的.这是一个更简单的解决方案,这个问题的问题甚至不存在!

Preface Feb 2015 If you are still using Entity Framework EDMX, please do yourself a favor and checkout using Entity Framework Code First instead. The difference is that your tables are created from your model classes, rather than in EDMX where your model classes are created with your tables. It's an all around easier solution, and the problem in this question doesn't even exist!

使用 MVC 5 开始使用 Entity Framework 6 Code First

我有一个现有的 SQL 数据库,我使用 ADO.NET Enity 数据模型作为模型.我正在尝试将一些 CRUD 功能构建到我的 MVC 应用程序中.

I have an existing SQL database, and I am using ADO.NET Enity Data Model for the model. I am trying to build some CRUD features into my MVC application.

在我找到的有关该主题的所有教程中,他们从头开始构建模型并将属性添加到模型类中.例如:

In all the tutorials I have found on the subject, they build the model from scratch and add the attributes to the model class. For example:

    [Required]
    [StringLength(10)]
    public string Name { get; set; }

然而,模型类是自动生成的,所以我认为改变它们是一个坏主意(如果数据库模型被刷新,无论如何都会被覆盖).

However, the model classes are auto-generated, so I think changing them is a bad idea (and will get written over anyway if the the database model is refreshed).

我将如何添加验证属性?

How would I add validation attributes?

推荐答案

您可以创建一个分部类,与 EF 生成的类分开,用于存储元数据.

You can create a partial class, separate from the EF generated class, to store the metadata in.

//Contact.cs - The original auto-generated file 
[System.ComponentModel.DataAnnotations.MetadataType(typeof(ContactMetadata))]
public partial class Contact
{
    public int ContactID { get; set; }
    public string ContactName { get; set; }
    public string ContactCell { get; set; }
}

//ContactMetadata.cs - New, seperate class

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
internal sealed class ContactMetadata
{
    [Required(ErrorMessage = "Name is required.")]
    [StringLength(5)]  
    public string ContactName;
}

这篇关于使用实体框架数据模型添加验证属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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