Friday, April 19, 2024
HomeC#EF Core Mapping with TpH, Generic Varieties and Worth Conversion – csharp.christiannagel.com

EF Core Mapping with TpH, Generic Varieties and Worth Conversion – csharp.christiannagel.com


EF Core has highly effective choices to map your area mannequin to a relational database. On this article, I’ll present you find out how to use the Fluent API to configure a hierarchy of generic lessons to map to a single desk, and to transform a group to a retailer a single string within the database.

Database tables

The Mannequin

The mannequin that’s outlined defines the categories GameData, and MoveData. The GameData class specifies a couple of easy properties in addition to a property of sort ICollection that specifies a relationship. Utilizing the first constructor syntax, the C# compiler creates init-only properties and a constructor that initializes the properties. EF Core doesn’t require parameterless constructors. Nonetheless, relations can’t be assigned utilizing the constructor. The Strikes property of sort ICollection is initialized with a Checklist. On this scneario, the gathering comprises sorts deriving from the MoveData class.

With this pattern, the ‘MoveData’ sort is of particular curiosity. MoveData is an summary base class. The generic model MoveData is derived from MoveData. The MoveData class specifies a property of sort ICollection that has a group of fields of a single recreation transfer. The sort TField is a generic parameter which permits creating completely different recreation sorts. For instance, a transfer can encompass a listing of various colours, or with one other extra advanced recreation sort, a listing of various shapes and colours. The values of the MoveData class in addition to the generic lessons deriving from it needs to be saved in a single desk. The sector values specified as a group property needs to be saved in the identical desk as a single string.

Models

The categories that will probably be used for the generic sort parameter TField are the data ColorField and ShapeAndColorField. ColorField wraps a coloration specified by a string, ShapeAndColorField wraps two strings specifying a form and a coloration. These sorts will probably be mentioned later in additional element.

EF Core Fluent API

Specifying the mapping of the GameData sort is finished utilizing the Fluent API. The desk the category is mapped to is Video games, the first key and column properties are specified as proven within the following code snippet.

Fluent API for GameData

Specifying a One-to-Many Relation

The relation between GameData and MoveData is specified with the next code snippet. You may specify a one-to-many relation utilizing the HasOne and WithMany strategies. Utilizing DeleteBehavior.Cascade specifies that if a recreation is deleted, the sport strikes will probably be deleted as properly. There’s a one-to-many relation specified these two sorts, and a cascade delete. The a recreation is deleted, all its strikes are deleted as properly.

Fluent API for MoveData

Utilizing Desk per Hierarchy Mapping Technique

Utilizing the Desk per Hierarchy (TpH) TpH hierarchy mapping it’s potential to map a hierarchy of sorts to a single desk. Utilizing the HasDiscriminator technique, the column might be specified that will probably be used as a differentiator column to offer EF Core the knowledge which sorts needs to be created on studying the info. The HasDiscriminator technique is used along with HasValue. HasDiscriminator returns a DiscriminatorBuilder. HasValue is a technique of this builder that’s used to specify the worth that needs to be saved throughout the discriminator column when an occasion of the desired sort is saved. With the pattern code, the worth coloration is saved with a MoveData occasion, and the worth form is saved with a MoveData occasion.

Specifying TpH mapping

> EF Core additionally helps the Desk per Kind (TpT) and Desk per Concrete Kind (TpC) hierarchies. With TpT for each sort a distinct desk is created. With TpC for all concrete sorts a single desk is mapped. Thus, summary sorts are usually not mapped to a desk.

Changing Values

EF Core helps customized conversions from a .NET sort to a column since EF Core 5.0 with the strategy HasConversion. Utilizing this technique, two delegates might be assigned to transform the .NET sort to a column, and the opposite approach round.

Earlier than specifying the conversion, the categories have to be convertable. The categories that needs to be saved inside a single string are the ColorField and the ShapeAndColorField data. To transform them to a string, the ToString technique is overridden:

Overriding ToString

To create a ColorField or ShapeAndColorField occasion from a string, the static strategies Parse and TryParse can be utilized. Some sorts from .NET assist these strategies, for instance the Int32 sort to transform a string to a quantity. One of many new C# language options with C# 11 is the flexibility to outline static members in interfaces. This enables utilizing operators or different static members in generic lessons. The IParsable interface defines the Parse and TryParse strategies – as a static member.

The ColorField and ShapeAndColorField sorts implement this interface. The ColorField and ShapeAndColorField sorts might be transformed to a string, and a string might be transformed to a ColorField or ShapeAndColorField occasion.

Implementing IParsable

> Possibly you’re questioning concerning the NotNullWhen and MaybeNullWhen attributes. These attributes give hints to the compiler about nullable reference sorts conduct. These attributes act on the return sort of the TryParse technique. Utilizing NotNullWhen(true) offers the compiler the informatation if the TryParse technique returns true, the argument annotated with NotNullWhen(true) shouldn’t be null after the strategy returns. Which means that if the variable that’s assigned to the variable s shouldn’t be null after the strategy returns with a true worth, and the compiler mustn’t complain to require null checks. The TryParse technique returns the final paramter with the out modifier. Right here, the MaybeNullWhen(false) annotation is utilized. If the TryParse technique returns false, the compiler ought to complain about utilizing the out worth and not using a null verify. If TryParse fails, the pattern implementation returns null. The out sort shouldn’t be declared nullable, so the compiler doesn’t complain about null checks if the TryParse technique doesn’t return false.

With the pattern code, conversion to and from a string with the ColorField and the ShapeAndColorField shouldn’t be the one requirement. The MoveData lessons makes use of a group of those sorts that must be transformed. To do that, the MappingExtensions class defines the extension strategies ToFieldString and ToFieldCollection.
The ToFieldString technique invokes the ToString technique with each merchandise within the assortment and joins the outcomes with a colon. The ToFieldCollection technique splits the string on the colon and invokes the Parse technique on each merchandise. As a result of the Parse technique is now specified with the IParsable interface, the generic sort T can now be used to invoke this technique.

MappingExtensions invoking ToString and Parse

Now all what’s wanted is to specify the conversion. The following code snippet reveals the conversion for the Fields property of the MoveData class to invoke the ToFieldString technique utilizing the ICollection fields parameter, ant the ToFieldCollection technique utilizing the string fields parameter.

Specifying the conversion with HasConversion

> As a substitute of changing the ColorField and ShapeAndColorField sorts to a string, and again, the Fields property might be mapped to a JSON column. How ths characteristic can be utilized will probably be proven in a future article.

Take away

EF Core provides a strong mapping from the article mannequin to relational databases. It’s not solely potential to make use of constructors with arguments, but in addition map inherited lessons to tables – as proven with the desk per hierarchy mapping. The pattern code makes use of generic lessons and an summary base class which all are mapped to the identical desk. Utilizing worth conversions, it’s potential to map advanced sorts to a single worth. Worth conversion can be an effective way to map enum values to a illustration within the database.

With this text I’ve additionally proven an awesome new C# 11 characteristic – the flexibility to outline static members in interfaces. The IParsable interface is utilized in a generic extension technique to transform a string to a group of a generic sort by parsing a string to create situations of the generic sort.

Get pleasure from studying and programming!

Christian

When you loved this text, I’m grateful in the event you assist me with a espresso. Thanks!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments