Replacing Entity Framework Classes With Record Types | Jamie Dixon's Home
source link: https://jamessdixon.com/2018/08/31/replacing-entity-framework-classes-with-record-types/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Replacing Entity Framework Classes With Record Types
August 31, 2018 Leave a comment
I recently have been working on a mixed-language project (C# and F#) where the original implementation used the Entity Framework reverse POCO generator found here. If you are not familiar, this Visual Studio add-in uses a T4 template to inspect a database and generate Entity Framework classes based on the tables that are located in the database. The generator created two files for a given table: the entity and a class for configuration.
At the time, it probably was the best way to generate the hundreds of classes that were needed for the C# project. However, now that we are introducing F# to the code base, it made sense to use the right tool for the job.
AFAIK, there are two ways you can use F# to do ORM. Way #1 is to use type providers and way #2 is to have record types and hand-roll the connectivity. I would have preferred to use a type provider to expose the database types in two lines of code, but since these types are being used by other C# and VB.NET projects, this was not possible.
Option 2 was to create record types. Instead of hand writing the types, I decided to create a quick script that turns C# classes into F# types. Since the each individual C# class was in its own file, the script traverses a directory and pull all of the C# files:
Within each file, I needed to get both the type name and then the properties. Getting the name was a text search for “public class” and the attributes was “get;set”
With the parsed values (1 class name and an array of attributes), I could then create the type name and the type attributes:
With those values, set, I could then create the types:
and then it was just a matter of putting it all together:
With these values, I could create a single file and have all of my domain objects in 1 place – with about 95% less noise code.
Git is here
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK