A wrapper against Guid.
-
- 2.1. Files
-
- 4.1. System.UuidConverters
- 4.2. Microsoft.EntityFramework.UuidConverters
- 4.2.1. Setup
I made this gist to solve the issue of serializing Guid to string for web apis.
It makes them url friendly with the usage of Base64
and short (22 characters).
It also solve the problem of desrializing them back to Guid from the 22 characters string.
All while mentaining storing them as plain Guid in Database.
Download this gist then copy files to your project.
Remove, add or edit whatever you want.
Use in you code:
public class Book
{
public Uuid Id { get; set; }
public required string Name { get; set; }
// Maybe this attribute is not necessary. I need to test it.
[JsonConverter(typeof(UuidConverters.NullableJsonConverter))]
public Uuid? PublisherId { get; set; }
}
Uuid.cs
: main file.UuidStringUtils.cs
provide string utils. See more in Utils section.IEquatable.cs
provides necessary implementation ofIEquatable
interfaces.TypeConverter.cs
provides implementation ofTypeConverter
.JsonConverter.cs
provides implementation ofJsonConverter
.EfConverter.cs
provides implementation ofValueConverter
.EfConverterExtensions.cs
provides extensions for DbContext to supportUuid
.
Uuid provides:
New
to create new value.ValueOrNew
checks if value is valid for use. Returns new one if not.ValueOrDefault
checks if value is valid for use. Returns default empty if not.IsEmpty
to check if value is null, default or empty guid.
String Utils:
ToShortId
to convertUuid
to base64 22-character string.FromShortId
to convert string toUuid
if possible.StringIsNotValidShortId
to check whether it's possible to convert string back toUuid
or not.
Converters are provided by System.UuidConverters
and Microsoft.EntityFramework.UuidConverters
classes.
Note
All converters are using ToString()
when converting to string value so implementation is unified accross them.
If you feel you need to change anything, you can do it there.
This class provides implementation for:
- TypeConverter: applied by
[TypeConverter]
annotation. No need for extra setup. - JsonConverter: also applied by
[JsonConverter]
annotation. Might need to apply nullable converter.
This class provides an implementation of ValueConverter
for EF Core.
Usage with DbContext
:
public class DataContext : DbContext
{
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
base.ConfigureConventions(configurationBuilder);
// ... configs
configurationBuilder
.Properties<Uuid>()
.HaveConversion<UuidConverters.ToGuidValueConverter>();
configurationBuilder
.Properties<Uuid?>()
.HaveConversion<UuidConverters.ToNullableGuidValueConverter>();
// or to store as string
// configurationBuilder
// .Properties<Uuid>()
// .HaveConversion<UuidConverters.ToStringValueConverter>();
// configurationBuilder
// .Properties<Uuid?>()
// .HaveConversion<UuidConverters.ToNullableStringValueConverter>();
// ... configs
}
}