I am trying to persist against a MySql database using the Entity Framework the Code-First approach, I use in EF6 It does not give me an error, the problem is that it does not create the database or the table or add the records that I persist.
I show 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 send 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);
}
}
It gives me this error when I put in the console Enable-Migrations 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.`**
"The problem is that it does not create the database or the table or add the records that I persist".
Check several things:
To enable automatic migrations we have to execute the command
In the NuGet console (remembering that as the default project in the console we have to select the one that contains our context class).
When the command is executed
It is forced to create the DB and if it already exists and the elimination or destruction of the table structure and its data does not matter, you must add the Update-Database -force
I suggest looking at these commands and if you get an error message post it.
I solved it, I had taken the name of my class MyContex in the name of the connection when I should have put demozmarket
ConnectionString