EntityFramework – Migrations Gotchas

Wanting to be a little more thrifty on a side project, I decided to roll with MySQL and EntityFramework. There were a few gotchas, outside of the normal tutorial and I’m just putting this out here to save time for anyone else who may have had to deal with the issues I ran across.

Data Model defined in a separate library

Most of the 101 examples have the data model included in the MVC, WebAPI or Console/UI project that is typically the startup project. However, if you have your data model defined in a separate project don’t forget to add the “-StartupProjectName” argument when invoking any of the migration commands.

ex:

enable-migrations -StartupProjectName [DataModelLibName] -ProjectName [DataModelLibName]
add-migration -StartupProjectName [DataModelLibName] -ProjectName [DataModelLibName]
update-database -StartupProjectName [DataModelLibName] -ProjectName [DataModelLibName]

This argument is actually telling the migration command where to look for the configuration of the providers and the target database to migrate. If you have everything configured in the shell startup project, then you’re probably fine and won’t have witnessed the issues I ran across. However, if you have multiple providers and/or are testing a new provider, it helps to keep that isolated in a configuration in the library before pushing it to the actual startup project configuration.

Code first classes with DateTimeOffset fields

As of the MySQL 6.9.10 connector, there is no support for the DateTimeOffset type and there are no plans for from what I’ve read. However, if you already have lots of models that use that type you can add the following code to your models to preserve most of your existing logic and still have it serialize into the database accordingly.

public class Foo
{
  ...
  [NotMapped]
  public DateTimeOffset UpdatedAt { get; set; }
  public DateTime UpdatedAtUtc {
    get => this.UpdatedAt.UtcDateTime;
    set => this.UpdatedAt = value.ToLocalTime();
  ...
}

Keep on coding on!


Posted

in

by

Tags:

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.