Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using GTMPGameMode.GermanRealLife.Server.Model;
- using MySql.Data.Entity;
- using MySql.Data.MySqlClient;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Data.Entity;
- using System.Data.Entity.Infrastructure;
- using System.Data.Entity.Migrations;
- using System.Linq;
- namespace MySQLLinqExample.resources.mysql.Server.Models
- {
- [DbConfigurationType(typeof(MySqlEFConfiguration))]
- public class DefaultDbContext : DbContext
- {
- public DefaultDbContext(string connectionString) : base(connectionString)
- {
- //Database.SetInitializer(new MigrateDatabaseToLatestVersion<DefaultDbContext, MigrationConfiguration>(true, new MigrationConfiguration()));
- Database.SetInitializer(new MigrateDatabaseToLatestVersion<DefaultDbContext, MigrationConfiguration>());
- }
- public override int SaveChanges()
- {
- var entities = (from entry in ChangeTracker.Entries()
- where entry.State == EntityState.Modified || entry.State == EntityState.Added
- select entry.Entity);
- var validationResults = new List<ValidationResult>();
- foreach (var entity in entities)
- {
- if (!Validator.TryValidateObject(entity, new ValidationContext(entity), validationResults))
- {
- throw new ValidationException();
- }
- }
- return base.SaveChanges();
- }
- public DbSet<account> Accounts { get; set; }
- }
- public class ContextFactory : IDbContextFactory<DefaultDbContext>
- {
- private static string ConnectionString;
- public static void SetConnectionParameters(string serverAddress, string username, string password, string database, uint port = 3306)
- {
- var connectionStringBuilder = new MySqlConnectionStringBuilder()
- {
- Server = serverAddress,
- UserID = username,
- Password = password,
- Database = database,
- Port = port
- };
- ConnectionString = connectionStringBuilder.ToString();
- }
- private static DefaultDbContext _instance;
- public static DefaultDbContext Instance
- {
- get
- {
- if (_instance != null) return _instance;
- return _instance = new ContextFactory().Create();
- }
- private set { }
- }
- public DefaultDbContext Create()
- {
- if (string.IsNullOrEmpty(ConnectionString)) throw new InvalidOperationException("Please set the connection parameters before trying to instantiate a database connection.");
- return new DefaultDbContext(ConnectionString);
- }
- }
- internal sealed class MigrationConfiguration : DbMigrationsConfiguration<DefaultDbContext>
- {
- public MigrationConfiguration()
- {
- AutomaticMigrationsEnabled = true;
- AutomaticMigrationDataLossAllowed = true;
- SetSqlGenerator("MySql.Data.MySqlClient", new MySqlMigrationSqlGenerator());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement