EF使用两个DbContext的例子

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/WuLex/article/details/77968722

类图:

这里写图片描述

UserModel.cs实体类

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MySQL
{
    public class UserModel
    {
        [Key]
        public int UserId { get; set; }

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

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

Configuration.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.Migrations;

namespace MySQL
{
    internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            ContextKey = "MySQL.ApplicationDbContext";

        }

        protected override void Seed(ApplicationDbContext context)
        {

        }
    }

    internal sealed class MySQLConfiguration : DbMigrationsConfiguration<MySQLDbContext>
    {
        public MySQLConfiguration()
        {
            AutomaticMigrationsEnabled = true;
            ContextKey = "MySQL.MySQLDbContext";
            // 注册mysql代码生成器 
            SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
        }

        protected override void Seed(MySQLDbContext context)
        {

        }
    }
}

ApplicationDbContext.cs

using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MySQL
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(string connectionString)
            : base(connectionString)
        {

        }
        public DbSet<UserModel> UserModels { get; set; }
    }
}

MySQLDbContext.cs

using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Data.Common;
using MySql.Data.Entity;

namespace MySQL
{
[DbConfigurationType(typeof(MySqlEFConfiguration))]
    public class MySQLDbContext : DbContext
    {
        public MySQLDbContext(): base("Server=localhost;Database=test;uid=root;pwd=123456;")
        { }
        public DbSet<UserModel> UserModels { get; set; }
    }
}

IRepository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MySQL
{
    public interface IRepository<T> : IDisposable
            where T : class
    {
        IEnumerable<T> GetAll(); 
        T Get(int id);
        void Create(T item);
        void Update(T item);
        void Delete(int id);
        void Save();
    }
}

SQLRepository.cs

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MySQL
{
    public class SQLRepository : IRepository<UserModel>
    {
        private ApplicationDbContext db;

        public SQLRepository(string connString)
        {
            this.db = new ApplicationDbContext(connString);
        }

        public IEnumerable<UserModel> GetAll()
        {
            return db.UserModels;
        }

        public UserModel Get(int id)
        {
            return db.UserModels.Find(id);
        }

        public void Create(UserModel item)
        {
            db.UserModels.Add(item);
        }

        public void Update(UserModel item)
        {
            db.Entry(item).State = EntityState.Modified;
        }

        public void Delete(int id)
        {
            UserModel item = db.UserModels.Find(id);
            if (item != null)
                db.UserModels.Remove(item);
        }

        public void Save()
        {
            db.SaveChanges();
        }

        private bool disposed = false;

        public virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    db.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

MySQLRepository.cs

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MySQL
{
    public class MySQLRepository : IRepository<UserModel>
    {
        private MySQLDbContext db;

        public MySQLRepository()
        {
            this.db = new MySQLDbContext();
        }

        public IEnumerable<UserModel> GetAll()
        {
            return db.UserModels;
        }

        public UserModel Get(int id)
        {
            return db.UserModels.Find(id);
        }

        public void Create(UserModel item)
        {
            db.UserModels.Add(item);
        }

        public void Update(UserModel item)
        {
            db.Entry(item).State = EntityState.Modified;
        }

        public void Delete(int id)
        {
            UserModel item = db.UserModels.Find(id);
            if (item != null)
                db.UserModels.Remove(item);
        }

        public void Save()
        {
            db.SaveChanges();
        }

        private bool disposed = false;

        public virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    db.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

Program.cs

using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MySQL
{
    class Program
    {
        private static string connectionStr = "Server=WU-PC;Database=Test;user id=sa;Password =123456;MultipleActiveResultSets=true";
        private static string connectionMySQLStr = "Server=localhost;Database=test;uid=root;pwd=123456;";
        private static IRepository<UserModel> repo;
        private static bool useMySQl = true;
        static void Main(string[] args)
        {
            // 创建SQL数据库
            MigrateDb();
            // 创建MySQL数据库
            MigrateMySQLDb();
            // 选择 repository
            if (useMySQl)
            {
                repo = new MySQLRepository();
            }
            else
            {
                repo = new SQLRepository(connectionStr);
            }
            // 使用 repository
            using (repo)
            {

                repo.Create(new UserModel { UserName = "Test", Gender = "Test" });
                repo.Save();
                foreach (var u in repo.GetAll())
                {
                    //Console.WriteLine($"{u.UserId}.{u.UserName} - {u.Gender}");
                    Console.WriteLine(string.Format("{0}.{1} - {2}", u.UserId, u.UserName, u.Gender));
                }
            }
            Console.Read();
        }
        public static void MigrateDb()
        {
            var configuration = new Configuration();
            configuration.TargetDatabase = new DbConnectionInfo(connectionStr, "System.Data.SqlClient");
            var migrator = new DbMigrator(configuration);
            migrator.Update();
        }
        public static void MigrateMySQLDb()
        {
            var configuration = new MySQLConfiguration();
            configuration.TargetDatabase = new DbConnectionInfo(connectionMySQLStr, "MySql.Data.MySqlClient");
            var migrator = new DbMigrator(configuration);
            migrator.Update();
        }
    }
}

运行结果:

这里写图片描述


这里写图片描述


这里写图片描述

猜你喜欢

转载自blog.csdn.net/WuLex/article/details/77968722
今日推荐