new extension methods

This commit is contained in:
jojo aquino 2024-12-16 17:27:27 +00:00
parent fb183f8660
commit c0b77acb42
5 changed files with 72 additions and 1 deletions

View File

@ -0,0 +1,44 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace EnotaryoPH.Data.Extensions
{
public static class ModelBuilderExtension
{
public static ModelBuilder UseValueConverterForType<T>(this ModelBuilder modelBuilder, ValueConverter converter) => modelBuilder.UseValueConverterForType(typeof(T), converter);
public static ModelBuilder UseValueConverterForType(this ModelBuilder modelBuilder, Type type, ValueConverter converter)
{
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
// note that entityType.GetProperties() will throw an exception, so we have to use reflection
var properties = entityType.ClrType.GetProperties().Where(p => p.PropertyType == type);
foreach (var property in properties)
{
modelBuilder.Entity(entityType.Name).Property(property.Name)
.HasConversion(converter);
}
}
return modelBuilder;
}
public class DateTimeKindValueConverter : ValueConverter<DateTime, DateTime>
{
public DateTimeKindValueConverter(DateTimeKind kind, ConverterMappingHints mappingHints = null)
: base(
v => v.ToUniversalTime(),
v => DateTime.SpecifyKind(v, kind),
mappingHints)
{
}
}
public static void SetDefaultDateTimeKind(this ModelBuilder modelBuilder, DateTimeKind kind)
{
modelBuilder.UseValueConverterForType<DateTime>(new DateTimeKindValueConverter(kind));
modelBuilder.UseValueConverterForType<DateTime?>(new DateTimeKindValueConverter(kind));
}
}
}

View File

@ -0,0 +1,9 @@
namespace EnotaryoPH.Web.Common.Extensions
{
public static class DateTimeExtensions
{
public static DateTime ToUTC(this DateTime? dte) => dte.GetValueOrDefault().ToUTC();
public static DateTime ToUTC(this DateTime dte) => new(dte.Ticks, DateTimeKind.Utc);
}
}

View File

@ -0,0 +1,7 @@
namespace EnotaryoPH.Web.Common.Extensions
{
public static class StringExtensions
{
public static string DefaultIfEmpty(this string s, string defaultValue) => !string.IsNullOrWhiteSpace(s) ? s : (defaultValue ?? string.Empty);
}
}

View File

@ -0,0 +1,9 @@
using System.Runtime.CompilerServices;
namespace EnotaryoPH.Web.Common.Helpers
{
public static class FullName
{
public static string Of<T>(T _, [CallerArgumentExpression("_")] string fullName = "") => fullName;
}
}

View File

@ -1 +1,3 @@
global using EnotaryoPH.Web.Common.Extensions; global using EnotaryoPH.Web.Common.Extensions;
global using EnotaryoPH.Web.Common.Helpers;
global using EnotaryoPH.Web.Common.Services;