Saturday, May 23, 2015

Database already Exists? Still chance is there for Code First!

Few days ago we were trying to implement one API which will talk to one existing database.  Now, developer/industry is very crazy with Code first approach in Entity Framework.  The general approach behind code first is , If the project is brand new.

In our case, The project was brand new but not database…!!!  .Shall we go for code first still or simply we will generate model from existing database?

Hold on, there is chance to implement your domain model from database using Entity Framework and that too automated.

Select Code First from database option in time of adding EDM file. Don’t worry It will not add that 
file in solution.


This option is available from Entity Framework 6 +


Choose your database and server here.


And once you finish model add operation , you will find that Entity classes is added in your solution. In my case my Dummy database contains test class and that is reflected here.

namespace Routing.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("test")]
    public partial class test
    {
        public int id { get; set; }

        public string name { get; set; }
    }
}

And here is scaffolding context class.

namespace Routing.Models
{
    using System;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;

    public partial class Dummy : DbContext
    {
        public Dummy()
            : base("name=Dummy")
        {
        }
        public virtual DbSet<test> tests { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<test>()
                .Property(e => e.name)
                .IsUnicode(false);
        }
    }
}

No comments:

Post a Comment