Open Closed

Save empty string as null in database #653


User avatar
0
ademaygun created
  • ABP Framework version: v3.3.1
  • UI type: Angular
  • Tiered (MVC) or Identity Server Seperated (Angular): no I am using postgres database and I want the if values are set with empty strings, they should automatically become null. So, I overrode SaveChanges() methods in MyStoreDbContext (in EntityFrameworkCore project) and add an method that called RemoveEmptyStrings() from* stackoverflow and my problem fixed. But is this best solution or does ABP provide any solution to this empty string problem?
public void RemoveEmptyStrings()
{
    // Look for changes
    this.ChangeTracker.DetectChanges();

    // Loop through each entity
    foreach (var entity in this.ChangeTracker.Entries())
    {
        // Use reflection to find editable string properties
        var properties = from p in entity.Entity.GetType().GetProperties()
            where p.PropertyType == typeof(string)
                  && p.CanRead
                  && p.CanWrite
            select p;

        // Loop through each property and replace empty strings with null
        foreach (var property in properties)
        {
            if (string.IsNullOrWhiteSpace(property.GetValue(entity.Entity, null) as string))
                property.SetValue(entity.Entity, null, null);
       }
    }
}
  • Exception message and stack trace:
  • Steps to reproduce the issue:

1 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi ademaygun

    I think override the ApplyAbpConcepts method is a good way.

    https://github.com/abpframework/abp/blob/32402a99b07ea994efe1880e0655eff3c73e2166/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/AbpDbContext.cs#L261

Made with ❤️ on ABP v9.1.0-preview. Updated on November 11, 2024, 11:11