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.csprovide string utils. See more in Utils section.IEquatable.csprovides necessary implementation ofIEquatableinterfaces.TypeConverter.csprovides implementation ofTypeConverter.JsonConverter.csprovides implementation ofJsonConverter.EfConverter.csprovides implementation ofValueConverter.EfConverterExtensions.csprovides extensions for DbContext to supportUuid.
Uuid provides:
Newto create new value.ValueOrNewchecks if value is valid for use. Returns new one if not.ValueOrDefaultchecks if value is valid for use. Returns default empty if not.IsEmptyto check if value is null, default or empty guid.
String Utils:
ToShortIdto convertUuidto base64 22-character string.FromShortIdto convert string toUuidif possible.StringIsNotValidShortIdto check whether it's possible to convert string back toUuidor 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
}
}