实体框架核心2-在数据库中将空字符串另存为null [英] Entity Framework Core 2 - save empty string as null in database

查看:85
本文介绍了实体框架核心2-在数据库中将空字符串另存为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中使用Entity Framework Core 2。我的数据库中有很多可为空的字符串列。

I'm using Entity Framework Core 2 in my application. I have a lot of nullable string columns in my database.

问题是我想将空字符串另存为 NULL 数据库。

The problem is that I want to save empty strings as NULL in the database.

在旧版本的EF中,我使用了 IDbCommandInterceptor 来实现拦截器,但是在EF Core 2中,我不使用不知道该怎么写吗?

In old versions of EF, I used a IDbCommandInterceptor for implementing an interceptor, but in EF Core 2, I don't know how to write one ?

推荐答案

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

There is a new IDbCommandInterceptor interface that should be able to handle this, but it looks complicated.

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

A simple approach is be to write a function to remove empty strings, and then call it before data is saved within your DbContext class.

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

记住要覆盖每个<$ c $版本c> SaveChanges(), SaveChanges(bool) SaveChangesAsync() code> DbContext 类。

Remember to override each version of SaveChanges(), SaveChanges(bool), SaveChangesAsync() in your DbContext class.

public override int SaveChanges()
{
    // Replace empty strings with null
    this.RemoveEmptyStrings();

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

这篇关于实体框架核心2-在数据库中将空字符串另存为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆