I'm trying to use Entity Framework with MySQL. I've just installed MySQL Installer for Windows which includes MySQL Connector for .NET.
I can't find any documentation on how to actually use this thing, so I've been cobbling pieces together from various tutorials. It appears I need the references for MySql.Data and MySql.Data.Entity for EF6 (screenshot).
Then I stole this source code from some random project which is the only reference I could find to MySqlConnectionFactory:
class ImgSigDbConfig : DbConfiguration
{
public ImgSigDbConfig()
{
base.AddDependencyResolver(new MySqlDependencyResolver());
base.SetProviderFactory(MySqlProviderInvariantName.ProviderName, new MySqlClientFactory());
base.SetProviderServices(MySqlProviderInvariantName.ProviderName, new MySqlProviderServices());
base.SetDefaultConnectionFactory(new MySqlConnectionFactory());
base.SetMigrationSqlGenerator(MySqlProviderInvariantName.ProviderName, () => new MySqlMigrationSqlGenerator());
base.SetProviderFactoryResolver(new MySqlProviderFactoryResolver());
base.SetManifestTokenResolver(new MySqlManifestTokenResolver());
}
}
I couldn't figure out how to set my database credentials anywher ein there, but apparently you can pass them in when constructing the DbContext:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ImgSimContext>());
var conn = new MySqlConnectionStringBuilder
{
Server = "localhost",
UserID = "root",
Password = "pass",
Database = "ImgSig"
};
using (var db = new ImgSimContext(conn.ToString()))
{
SqlConnection.ClearAllPools();
db.Database.Initialize(force: true);
Now I've created a very simple POCO:
internal class ImgSig
{
[Key, Required]
public int Id { get; set; }
[Index, StringLength(16), Required]
public byte[] Hash { get; set; }
}
But when it hits db.Database.Initialize an exception is thrown:
BLOB/TEXT column 'Hash' used in key specification without a key length
Which makes perfect sense because in MySQL you have to set the key length for any blob/text fields (although it would be nice to see what SQL it's trying to run).
So my questions are:
- How can I change the data type of
Hashto a fixed lengthbinary(16)? - How can I set the key length (preferably using attributes)?