3

I have a project on .NET 4.8 and EF 6.4.4. We are gradually migrating to .Net Core but during the process can I create a .NET Core data context class, EF Core and point both to same entities?

Toolkit
  • 10,779
  • 8
  • 59
  • 68
  • Yes but I would recommend you place the entities (models) in a shared project with the target frameworks of netstandard2.0 and net4.8. Make sure there is no EF specific code in your models, they should be pure POCO types (plain old clr objects). All mappings should be done using fluent mappings in your EF implementations. – Igor Jan 08 '21 at 14:49
  • seems like NET Core can't work with netstandard2.0 – Toolkit Jan 08 '21 at 14:52
  • What version of .net core are you using? – Igor Jan 08 '21 at 14:54
  • my start is 4.8 and EF 6.4.4, I am looking for any combination of Core and Standard to reuse existing entities – Toolkit Jan 08 '21 at 14:57
  • I have a .NET Core 3.1 project that references a project that targets .NET Standard 2.0. No problems here so I am not sure what you mean that it cant work. – Igor Jan 08 '21 at 15:01
  • .NET Core 3.1 with EF Core? – Toolkit Jan 08 '21 at 15:05
  • .net core 3.1 (its an mvc project) → .net standard 2.0 (uses EF core) → .net standard 2.0 (shared poco types). – Igor Jan 08 '21 at 15:07
  • And then a .net 4.8 framework projects that then also use the same shared poco library. – Igor Jan 08 '21 at 15:07
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/227045/discussion-between-toolkit-and-igor). – Toolkit Jan 08 '21 at 15:07
  • What flow are you using? Code first? Db first? Model first? – Artur Jan 08 '21 at 15:12
  • @Artur Code first – Toolkit Jan 08 '21 at 16:37

1 Answers1

1

Yes, you can. Refer to the diagram below.

  1. Convert all libraries to .netstandard2.0
  2. Start by moving all models to separate project.
  3. Then create new project where you are going to migrate your dal classes to EF Core (I'd recommend to keep the same namespace in Dal.csproj and Dal.Core.csproj so consumers won't be affected).
  4. Move your first dal class from Dal.csproj to Dal.Core.csproj. Now Stage + Commit - this is very important step, otherwise you will loose git history for this class. Now you can do all required changes to make it work with new DbContext
  5. Once you finish all migrations move everything from Dal.Core.csproj back to Dal.csproj and remove Dal.Core.csproj project. Do not forget to stage changes before commit so git will recognize moved files as rename rather than delete+add.

Tip: make sure you are aware of Cartesian Explosion Problem in EF Core 3

Note: if you are working in Model First approach with EDMX file that's not supported in EF Core, you can't convert the project with EDMX to netstandard2.0 and should keep it as net48.

enter image description here

Artur
  • 4,595
  • 25
  • 38