简体   繁体   中英

How to use AutoMapper with Entity Framework Database First approach

I am working on MVC 5, Entity Framework with Db First Approach. Whenever i use

public class Customer
{
    [Required]
    public virtual string CustomerID { get; set; }

    [Required]
    [StringLength(15)]
    public virtual string CompanyName { get; set; }

    public virtual string Address { get; set; }

    public virtual string City { get; set; }

    public virtual string PostalCode { get; set; }

    [Country(AllowCountry="USA")]
    public virtual string Country { get; set; }

    [Phone]
    public virtual string Phone { get; set; }
}

for Validation in Entity Framework generated class and if i update my .edmx file i lost all code that i was written. Someone suggest me use Auto-mapper. I try to find some basic example but i didn't get. Guide me. How to start and where from? I am new in MVC, Entity Framework.

There is another approach to retain the validation attribute code even if you update the model. In the Models folder, add a class named Metadata.cs (class that contain all of the validation attributes).

 using System; using System.ComponentModel.DataAnnotations; namespace YourProjectName.Models { public class CustomerMetadata { [Required] public virtual int CustomerId { get; set; } [Required] [StringLength(15)] public virtual string CompanyName { get; set; } } } 

Next, you must associate the model classes with the metadata classes.For that In the Models folder, add a class named PartialClasses.cs .

 using System; using System.ComponentModel.DataAnnotations; namespace YourProjectName.Models { [MetadataType(typeof(CustomerMetadata))] public partial class Customer { } } 

Source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM