实体框架核心2 - 在db中保存空字符串为null。

问题描述 投票:2回答:1

我在应用中使用实体框架核心2.我的db上下文中有很多null able字符串列,问题是我想在db中保存空字符串为null.在旧版本的Ef中,我使用IDbCommandInterceptor实现拦截器,但在Ef核心2中,我不知道如何写一个?

entity-framework entity-framework-core interceptor
1个回答
0
投票

有一个新的 IDbCommandInterceptor 接口应该能够处理这个问题,但它看起来很复杂。

一个简单的方法是写一个函数来删除空字符串,然后在DbContext类中保存数据之前调用它。

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);
       }
    }
}

记得在你的DbContext类中覆盖SaveChanges()、SaveChanges(bool)、SaveChangesAsync()的每个版本。

public override int SaveChanges()
{

    // Replace empty strings with null
    this.RemoveEmptyStrings();

    // Continue with base functionality
    return base.SaveChanges();

}
© www.soinside.com 2019 - 2024. All rights reserved.