Generate database model by code and database model by code

Source: Internet
Author: User
Tags connectionstrings

Generate database model by code and database model by code

The entity framework is used during project creation, and the database is mysql. Previously, the DB model was created first, and then added to the project. However, you need to update the database later. I learned from my colleagues: code make db model.

Required dll: MySql. data (6.9.5.0), MySql. data. Entity. EF6 (6.9.5.0 ),

System. Sata, System. Sata. DataSetExtension, System. Sata. SQLLite, System. Sata. SQLLite. EF6, System. Sata. SQLLite. Linq, EntityFramework, EntityFramework. SqlServer

Config file connection string:

<ConnectionStrings>
<Add name = "JobMasterDBConnection_MSSQL" connectionString = "Data Source = eiscng1_wqs1; Initial Catalog = JobMaster; Integrated Security = True" providerName = "System. Data. SqlClient"/>
<Add name = "JobMasterDBConnection_MYSQL" connectionString = "Data Source = 127.0.0.1; port = 3306; Initial Catalog = JobMaster; uid = root; pwd = Password! 01; "providerName =" MySql. Data. MySqlClient "/>
<Add name = "JobMasterDBConnection_SQLite" connectionString = "Data Source = DB \ JobMaster. local. db;" providerName = "System. Data. SQLite. EF6"/>
</ConnectionStrings>

Context and Migrations files:

 1 using System; 2 using System.Collections.Generic; 3 using System.Configuration; 4 using System.Data; 5 using System.Data.Entity; 6 using System.Data.Entity.Migrations; 7 using System.Data.Entity.ModelConfiguration; 8 using System.Data.Entity.ModelConfiguration.Conventions; 9 using System.Linq;10 using System.Text;11 12 namespace JobMaster.Libs.Models.DBContext13 {14     //[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]15     internal class JobMasterDBContext : DbContext16     {17         #region "Fields"18         public const string CNSTR_CONNECTIONNAME = "JobDispatcher_Database_Entry";19         public const string CNSTR_CONNECTIONNAME_MSSQL = "JobMasterDBConnection_MSSQL";20         public const string CNSTR_CONNECTIONNAME_MYSQL = "JobMasterDBConnection_MYSQL";21         public const string CNSTR_CONNECTIONNAME_SQLITE = "JobMasterDBConnection_SQLite";22         #endregion23 24         #region "Constructs"25         public JobMasterDBContext()26             : this(ConfigurationManager.AppSettings[CNSTR_CONNECTIONNAME])27         { }28 29         public JobMasterDBContext(string connectionName)30             : base(connectionName)31         {32             this.Configuration.LazyLoadingEnabled = false;33             this.Configuration.ProxyCreationEnabled = false;34         }35 36         static JobMasterDBContext()37         {38             switch (ConfigurationManager.AppSettings[CNSTR_CONNECTIONNAME])39             {40                 case CNSTR_CONNECTIONNAME_MSSQL:41                     break;42                 case CNSTR_CONNECTIONNAME_MYSQL:43                     DbConfiguration.SetConfiguration(new MySql.Data.Entity.MySqlEFConfiguration());44                     Database.SetInitializer<JobMasterDBContext>(new MigrateDatabaseToLatestVersion<JobMasterDBContext, JobMaster.Libs.Models.Migrations.JobMasterDBConfiguration>());45                     break;46                 case CNSTR_CONNECTIONNAME_SQLITE:47                     //Database.SetInitializer<JobMasterDBContext>(new DropCreateDatabaseAlways<JobMasterDBContext>());48                     break;49             }50         }51         #endregion52 53         #region "Propertiess"54         public DbSet<Agent> Agents { get; set; }55 56         public DbSet<Job> Jobs { get; set; }57 58         public DbSet<TestCase> TestCases { get; set; }59 60         public DbSet<Task> Tasks { get; set; }61 62         public DbSet<TaskAssignment> TaskAssignments { get; set; }63         #endregion64 65         #region "Events"66         protected override void OnModelCreating(DbModelBuilder modelBuilder)67         {68             modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();69             modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();70 71             //modelBuilder.Entity<EntityType>().MapToStoredProcedures();72 73             modelBuilder.Entity<TestCase>().Property(p => p.TaskID).IsOptional();74             modelBuilder.Entity<Task>().HasMany(p => p.TestCases).WithOptional().HasForeignKey(p => p.TaskID);75         }76         #endregion77     }78 }
namespace JobMaster.Libs.Models.Migrations{    using System;    using System.Data.Entity;    using System.Data.Entity.Migrations;    using System.Linq;    internal sealed class JobMasterDBConfiguration : DbMigrationsConfiguration<JobMaster.Libs.Models.DBContext.JobMasterDBContext>    {        public JobMasterDBConfiguration()        {            AutomaticMigrationsEnabled = true;            switch (System.Configuration.ConfigurationManager.AppSettings[JobMaster.Libs.Models.DBContext.JobMasterDBContext.CNSTR_CONNECTIONNAME])            {                case JobMaster.Libs.Models.DBContext.JobMasterDBContext.CNSTR_CONNECTIONNAME_MSSQL:                    break;                case JobMaster.Libs.Models.DBContext.JobMasterDBContext.CNSTR_CONNECTIONNAME_MYSQL:                    SetSqlGenerator("MySql.Data.MySqlClient.EF6", new MySql.Data.Entity.MySqlMigrationSqlGenerator());                    break;                case JobMaster.Libs.Models.DBContext.JobMasterDBContext.CNSTR_CONNECTIONNAME_SQLITE:                    break;            }        }        protected override void Seed(JobMaster.Libs.Models.DBContext.JobMasterDBContext context)        {            //  This method will be called after migrating to the latest version.            //  You can use the DbSet<T>.AddOrUpdate() helper extension method             //  to avoid creating duplicate seed data. E.g.        }    }}

Model:

using System;using System.Collections;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;using System.Linq;using System.Runtime.Serialization;using System.Text;using System.Threading.Tasks;using JobMaster.Libs.Models;using JobMaster.Libs.Models.ViewModels;using JobMaster.Libs.Utils;using JobMaster.Libs.Utils.Extensions;namespace JobMaster.Libs.Models{    [Table("tbl_Jobs")]    public class Job    {        #region "Constructs"        public Job() { }        #endregion        #region "Properties"        [Key]        [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]        public long ID { get; set; }        [MaxLength(100)]        public string Name { get; set; }        [MaxLength(300)]        public string Description { get; set; }        public Nullable<bool> EnableSliceSet { get; set; }        public Nullable<int> MinialSliceSize { get; set; }        [Required]        [MaxLength(300)]        public string PrepConfig { get; set; }        public Nullable<int> Priority { get; set; }        public Nullable<JobType> JobType { get; set; }        public Nullable<JobStatus> Status { get; set; }        public Nullable<int> TotalCount { get; set; }        public Nullable<int> TotalSuccess { get; set; }        public Nullable<int> TotalFailure { get; set; }        public Nullable<int> TotalTimeout { get; set; }        public Nullable<System.DateTime> CreateTime { get; set; }        public Nullable<System.DateTime> StartTime { get; set; }        public Nullable<System.DateTime> EndTime { get; set; }        public Nullable<System.DateTime> UpdateTime { get; set; }        #endregion        #region "Properties"        public virtual ICollection<TestCase> TestCases { get; set; }        public virtual ICollection<Task> Tasks { get; set; }        #endregion    }}

How to use:

JobMasterDBContext  dbcontext=new JobMasterDBContext();dbcontext.Jobs.add(new Job(){Name="test"});dbcontext.SaveChanges();


Note: You need to add the above Dll to the db project.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.