Skip to content

Entity Framework Model Mapping

Entity Framework 6 is pretty awesome, and there is probably a part of it that you are not fully aware of.

Let me introduce you to the EntityTypeConfiguration class.

With this class you can separate your model mappings from your DbContext.

Here is an example of the folder structure that works with this strategy.

EntityFrameworkMappingSolutionExample

Here is a simple step by step example of how to implement Entity Framework Model Mapping

Create your model

namespace EntityFrameworkExamples.Models
{
    public class User
    {
        public long Id { get; set; }

        public string Username { get; set; }

        public string Password { get; set; }
    }
}

User.cs

 

Set up your DbContext

using System.Data.Entity;
using EntityFrameworkExamples.Models;

namespace EntityFrameworkExamples.Data
{
    public class ApplicationContext : DbContext
    {
        public virtual IDbSet<User> Users { get; set; } 

        public ApplicationContext()
            : base("DefaultConnection")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // Get mappings from this assembly                                    
            modelBuilder.Configurations.AddFromAssembly(GetType().Assembly);

            base.OnModelCreating(modelBuilder);
        }
    }
}

ApplicationContext.cs

 

Setup your mapping using the EntityTypeConfiguration class.

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using EntityFrameworkExamples.Models;

namespace EntityFrameworkExamples.Mappings
{
    class UserMapping : EntityTypeConfiguration<User>
    {
        public UserMapping()
        {
            ToTable("Users");

            HasKey(m => m.Id);

            Property(m => m.Id).HasColumnName("ID").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(m => m.Username).HasColumnName("Username").IsRequired();
            Property(m => m.Password).HasColumnName("Password").IsRequired();
        }
    }
}

UserMapping.cs

 

Now we are ready to go!

Here is a UserService class that will use our configured context.

using System.Collections.Generic;
using EntityFrameworkExamples.Data;
using EntityFrameworkExamples.Models;

namespace EntityFrameworkExamples.Services
{
    public class UserService
    {
        private readonly ApplicationContext _context;

        public UserService(ApplicationContext context)
        {
            _context = context;
        }

        public IEnumerable GetUsers()
        {
            return _context.Users;
        }

        public User GetUser(long id)
        {
            return _context.Users.Find(id);
        }

        public User AddUser(User user)
        {
            var result = _context.Users.Add(user);

            _context.SaveChanges();

            return result;
        }

        public int UpdateUser(long id, User user)
        {
            var original = GetUser(id);

            if (original == null)
                return 0;

            var entry = _context.Entry(original);

            entry.CurrentValues.SetValues(user);

            return _context.SaveChanges();
        }

        public int RemoveUser(long id)
        {
            var user = GetUser(id);

            if (user == null)
                return 0;

            _context.Users.Remove(user);

            return _context.SaveChanges();
        }
    }
}

UserService.cs

Piece of cake, right?

You can use this style for any type of model. You can also add associations to models, but I shall save that for another day!

Published in.NETC#C#

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *