Skip to content

EntityFramewokReadModel

ZhangYang edited this page Sep 7, 2019 · 2 revisions

EntityFramework read model

To setup EventFlow Microsoft SQL Server integration, install the NuGet package EventFlow.MsSql

  1. Create a DbContext for you read model: RestAirlineReadModelContext

  2. Ideally we don't want to conigure connection string directly, because we want to get it from different place for each environment, for example in local we probably want to get it from settings:

"ReadModelConnectionString": "Server=tcp:127.0.0.1,1433;Database=RestAirlineRead;User Id=sa;Password=RestAirline123"

for production the application is running in docker, so connection string is come from enviroment varibles: ReadModelConnectionString=${READ_MODEL_DB:-Server=mssql.data;Database=RestAirlineRead;User Id=sa;Password=RestAirline123} To do this we add class RestAirlineReadModelDbContextProvider, configuration["ReadModelConnectionString"] will read settings by default and override by environment varibles in docker.

  1. ReadModelDbContextDesignFactory is used for creating migrations in local

  2. FakedEntityFramewokReadModelDbContextProvider is used for unit testing, when running testing will inject this in-memory DbContextProvider instead of connecting real SQL Server.

  3. Finally we use EntityFrameworkReadModelModule register services into DI container:

public class EntityFrameworkReadModelModule: IModule
{
    public void Register(IEventFlowOptions eventFlowOptions)
    {
        eventFlowOptions.ConfigureEntityFramework(EntityFrameworkConfiguration.New)
            .AddDefaults(typeof(EntityFrameworkReadModelModule).Assembly)
            .AddDbContextProvider<RestAirlineReadModelContext, RestAirlineReadModelDbContextProvider>()
            .UseEntityFrameworkReadModel<BookingReadModel, RestAirlineReadModelContext>()
            ;
    }
}

For some reason entity framework can not works well because Entity Framework read model can not load children entities during update, I will spike this latter.

Clone this wiki locally