MySql Entity Framework Code-Firsrt

3

I am trying to persist against a MySql database using the Entity Framework the Code-First approach, use in EF6 I do not get an error, The problem is that I do not create the database or the table or add the records I persist.

We show our implementation code.

App.config

<configuration>


<configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <connectionStrings>
    <add name="DemoContext" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;port=3306;database=demozmarket;uid=root;password=123456" />
  </connectionStrings>
  <entityFramework codeConfigurationType="DemoMySqlEntityFramework.MySqlEFConfiguration, DemoMySqlEntityFramework">
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework" >
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <!--<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />-->
      <provider invariantName="MySql.Data.MySqlClient"
              type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </providers>
  </entityFramework>
<system.data>
    <DbProviderFactories>
      <remove invariant="MySql.Data.MySqlClient" />
      <add name="MySQL Data Provider" 
           invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
  </system.data>
</configuration>

Maps (Fluent Api)

namespace DemoMySqlEntityFramework.Data.Modelo.Maps
{
    public class ClienteMap : EntityTypeConfiguration<Cliente>
    {
        public ClienteMap()
        {
            ToTable("Clientes");
            HasKey(c => c.ClienteId);
            Property(c => c.ClienteId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).HasColumnOrder(0);
            Property(c => c.RazonSocial).IsRequired().HasColumnType("varchar").HasMaxLength(100).HasColumnOrder(1);
            Property(c => c.Direccion).HasColumnType("varchar").HasMaxLength(100).HasColumnOrder(2);
            Property(c => c.Fecha).HasColumnOrder(3);
        }
    }
}

DbContext Class

namespace DemoMySqlEntityFramework.Data.Modelo
{

    public class DemoContext : DbContext
    {
        public DemoContext() : base("DemoZMarket")
        {
            Configuration.LazyLoadingEnabled = false;
            Configuration.ProxyCreationEnabled = false;
        }

        public DbSet<Cliente> Clientes { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new ClienteMap());
            base.OnModelCreating(modelBuilder);
            //modelBuilder.Entity<HistoryRow>().Property(h => h.MigrationId).HasMaxLength(100).IsRequired();
            //modelBuilder.Entity<HistoryRow>().Property(h => h.ContextKey).HasMaxLength(200).IsRequired();
        }
    }
}

Entities

public class Cliente
{
    public int ClienteId { get; set; }
    public string RazonSocial { get; set; }
    public string Direccion { get; set; }
    public DateTime? Fecha { get; set; }
}

Repository

public class ClienteReposotory
{
    public void Create(Cliente entity)
    {
        using (var context = new DemoContext())
        {
            context.Clientes.Add(entity);
            context.SaveChanges();
        }
    }
}

I sent you data

public partial class Form1 : Form
{
    private readonly ClienteReposotory _clienteReposotory = new ClienteReposotory();
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        var cliente = new Cliente()
        {
            RazonSocial = "COMERCIAL PEPITO",
            Direccion = "MI CASA",
            Fecha = new DateTime(1976, 08, 10)
        };

        _clienteReposotory.Create(cliente);

    }
}

I get this error when I put in the Enable-Migrations console or any other migrations command.

PM> Enable-Migrations -ContextTypeName  "DemoContext" -

EnableAutomaticMigrations
Checking if the context targets an existing database...
System.NullReferenceException: Referencia a objeto no establecida como instancia de un objeto.
   en MySql.Data.MySqlClient.MySqlProviderServices.GetDbProviderManifestToken(DbConnection connection)
   en System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
   en MySql.Data.Entity.MySqlManifestTokenResolver.ResolveManifestToken(DbConnection connection)
   en System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest)
   en System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
   en System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
   en System.Data.Entity.Internal.RetryLazy'2.GetValue(TInput input)
   en System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   en System.Data.Entity.Internal.LazyInternalContext.get_ModelBeingInitialized()
   en System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
   en System.Data.Entity.Utilities.DbContextExtensions.<>c__DisplayClass1.<GetModel>b__0(XmlWriter w)
   en System.Data.Entity.Utilities.DbContextExtensions.GetModel(Action'1 writeXml)
   en System.Data.Entity.Utilities.DbContextExtensions.GetModel(DbContext context)
   en System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase)
   en System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
   en System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration migrationsConfiguration)
   en System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
   en System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   en System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   en System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   en System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldInitialCreate(String language, String rootNamespace)
   en System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
   en System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action 

command)

**'Referencia a objeto no establecida como instancia de un objeto.'**
    
asked by Pedro Ávila 10.07.2017 в 01:12
source

2 answers

1

I solved it had taken the name of my class MyContex in the name of the connection when I had to put demozmarket

public DemoContext() : base("demozmarket")

ConectionString

<add name="demozmarket" providerName="MySql.Data.MySqlClient" connectionString="Server=127.0.0.1;Port=3306;Database=demozmarket;Uid=root;Pwd=xxxx" />
    
answered by 11.07.2017 / 06:35
source
2

"The problem is that I do not create the database or the table or add the records I persist."

Verify several things:

  • Did you enable automatic migrations?
  • To enable automatic migrations we have to execute the command

    Enable-Migrations –EnableAutomaticMigrations 
    

    In the NuGet console (remembering that as the default project in the console we have to select the one that contains our context class).

    Enable-Migrations -ContextTypeName  "NombreclaseDelContexto" -EnableAutomaticMigrations
    
  • If you enabled automatic migrations. Did you give the Update-Database command in the NuGet console?
  • When the command

    is executed
    Update-Database  
    

    The creation of the Bd is forced and if it already exists and it does not matter the elimination or destruction of the structure of the table and its data you must add the Update-Database -force

    I suggest looking at these commands and if you get an error message, post it.

        
    answered by 10.07.2017 в 07:35