Reputation: 315
I'm using ASP.NET Core 3.1 with Entity Framework. I'm trying to store byte arrays into a database. Of course, my MySQL database should support that, but Entity Framework doesn't seem to work.
Consider the following model:
public class User
{
[Key]
public int Id { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public byte[] Salt { get; set; }
public byte[] Password { get; set; }
[NotMapped]
public string PlainPassword { get; set; }
}
Now, whenever I use the package manager console to do Add-Migration InitialCreate
, I get the following output:
PM> Add-Migration InitialCreate
Build started...
Build failed.
Whenever I change the byte[]
to string
, it works, but the passwords are no strings. What should I do? Convert them to strings or is there another workaround? And if I should convert them to strings, what is the best way to convert them?
Upvotes: 0
Views: 3566
Reputation: 4819
Using Entity Framework Core 6.0 Preview 6 you can have pre-convention model configuration. That is you can configure for example that all strings will be stored as byte arrays:
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
configurationBuilder.Properties<string>()
.HaveConversion<byte[]>()
.HaveMaxLength(255);
configurationBuilder.IgnoreAny<INonPersisted>();
}
Upvotes: 0
Reputation: 171
Ok for this to work with MySQL I used the gist project that @YegorAndrosov made here https://gist.github.com/pwrigshi/ff5ccd5a4437d054b6712ec24d089d84 and for MySQL i Added only 2 Packages from NuGet (i tried Microsoft.EntityFrameworkCore package but it doesn't have UseMySQL in it's DbContextOptionsBuilder and i'm no expert in EF to solve this missing part)
here are the 2 packages that work
MySql.Data.EntityFrameworkCore (it's from Oracle !)
Microsoft.EntityFrameworkCore.Design
as i mentioned above the package (Microsoft.EntityFrameworkCore) doesn't seems to have a way to use MySQL, now the only change i made from that code in the link is pointing to MySQL instead of SqlServer in DbContext, and the ConnectionString itself ofcourse to match the MySQL server in my machine)
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL("Server=localhost;Port=3306;Database=test;Uid=mysql;Pwd=MyPass;");
base.OnConfiguring(optionsBuilder);
}
then on package manager console i did
PM> dotnet ef migrations add Init --project ConsoleApp1 --verbose
and after migration created i did
PM> dotnet ef database update --project ConsoleApp1 --verbose
it worked just fine, migration was created, then database created on MySQL server successfully.
Upvotes: 1