Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent from DataAnnotations Attributes being deleted in DataBase First Model

I have my asp.net mvc 3 application with entity framework and i used the Database First model to set it up.

My Steps below: 1. Genarated a database with tables 2. Created ADO.NET Entity Data Model file (.edmx) and imported the tables 3. inside the design i added a Code Generation item and used ADO.NET DbContext Generator 4. a Model1.tt holder as been made with all of the tables Models

I have edited the models and updated them with DataAnnotations Attributes (just for the example a well known one)

public class LogOnModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

Now when im making changes to the database and updating it to the edmx file all the models will be overwritten and the DataAnnotations Attributes will disapear.

my question: how can i use database first model and still edit the models for speciific validation like im free to do with code first model? (please no third party tools solution) thanks

like image 367
python Avatar asked Feb 10 '12 15:02

python


People also ask

How do you validate model data using DataAnnotations attributes?

ComponentModel. DataAnnotations namespace includes the following validator attributes: Range – Enables you to validate whether the value of a property falls between a specified range of values. RegularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.

Which Dataannotation is used for mandatory model fields?

We'll use the following Data Annotation attributes: Required – Indicates that the property is a required field. DisplayName – Defines the text to use on form fields and validation messages. StringLength – Defines a maximum length for a string field.

What is the attribute given for primary key in model class?

The Key attribute can be applied to a property in an entity class to make it a key property and the corresponding column to a PrimaryKey column in the database. The default convention creates a primary key column for a property whose name is Id or <Entity Class Name>Id .


2 Answers

You need to use buddy classes. See my dated but still useful article http://msdn.microsoft.com/en-us/library/ee256141(v=vs.98).aspx

like image 130
RickAndMSFT Avatar answered Oct 11 '22 21:10

RickAndMSFT


Use ViewModels in your Views. This will decouple your EF entities from your UI logic.

like image 23
jrummell Avatar answered Oct 11 '22 21:10

jrummell