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

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

问题描述

preface 2015年2月如果你还在使用实体框架EDMX,请使用实体框架code首先不是请你帮个忙和结算。所不同的是,你的表是从你的模型类创建的,而不是在你的模型类与你的表创建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!

<一个href=\"http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application\">Getting开始与实体框架6 code首先使用MVC 5

我有一个现有的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天全站免登陆