简体   繁体   English

如果实体中的字符串为null,则在SQL中使用默认值

[英]Use default value in SQL if string in entity is null

I have a project with database first approach and a SQL Server database. 我有一个使用数据库优先方法和SQL Server数据库的项目。

In one of tables I have a not nullable column with a default value as empty string: 在表之一中,我有一个不可为空的列,其默认值为空字符串:

[Comments] NVARCHAR(1024) NOT NULL DEFAULT ('')

Default value here should always be an empty string to completely support odata "Is not empty" filter which otherwise returns me records with null values which are really empty from business perspective. 这里的默认值应该始终是一个空字符串,以完全支持odata“ Is not empty”过滤器,否则将返回具有空值的记录,这些记录从业务角度来看实际上是空的。

In my model I also have a string property for this column: 在我的模型中,此列也有一个字符串属性:

public string Comments { get; set; }

Now what happens is: from frontend I may get null value if appropriate input is not filled with data and this value will be mapped into the entity which is then going to be inserted by EF. 现在发生的事情是:如果适当的输入未填充数据,从前端我可能会得到空值,并且该值将映射到实体中,然后由EF插入该实体。

In case if I just try to set a record with null "Comments" property instead of getting default value on SQL side I'm getting an exception. 如果我只是尝试设置具有空的“ Comments”属性的记录,而不是在SQL端获取默认值,那我将获得异常。

I tried to fix it by setting StoreGeneratedPattern for this column to Computed in EDMX. 我试图通过将此列的StoreGeneratedPattern设置为EDMX中的Computed来修复它。 Now I can insert records with nulls and I get default value but I get it every time, even if have a value in entity. 现在,我可以插入带有空值的记录,我将获得默认值,但是即使实体中具有值,我也会每次都获得它。

In other words computed StoreGeneratedPattern always ignores value of this property in entity and disabling StoreGeneratedPattern basically leaves me with no default value on the SQL side. 换句话说,计算出的StoreGeneratedPattern始终会忽略实体中此属性的值,并且禁用StoreGeneratedPattern基本上在SQL端没有默认值。

What I want is to solve this issue on backend in some nice way. 我想要以某种不错的方式在后端解决此问题。

  1. I don't want to solve it by just always sending empty string from frontend and adding validation to the backend that this property is never null. 我不想仅通过始终从前端发送空字符串并将验证添加到后端来解决此属性永远不会为null的问题。 It will force me to do the same for other clients (mobile client for example) and for every form and table where I meet the same situation. 这将迫使我对其他客户端(例如移动客户端)以及遇到相同情况的每个表格和表格执行相同的操作。

  2. I don't want to solve it by just doing something like: 我不想通过做类似的事情来解决它:

     entity.Comments = entity.Comments ?? string.empty; 

    on the backend. 在后端。 It will force me to do it in every place where I process this and other similar entities. 这将迫使我在我处理此实体和其他类似实体的每个地方都这样做。

  3. I don't want to solve it by using some interface for similar entities or by initialization of this property in constructor. 我不想通过对相似实体使用某些接口或在构造函数中初始化此属性来解决此问题。 I have one single T4 template which builds entity models for me from EDMX for decoupling reasons so all models are autogenerated and should never be customized. 我有一个单一的T4模板,出于去耦的原因,该模板可以从EDMX为我构建实体模型,因此所有模型都是自动生成的,永远不要定制。

The behaviour which I was expecting and which I would like to reach is as follows: 我期望并希望达到的行为如下:

if EF tries to insert a record with null value for this column, SQL Server uses DEFAULT, otherwise it inserts what the entity had. 如果EF尝试为此列插入具有空值的记录,则SQL Server使用DEFAULT,否则将插入实体所具有的内容。

Any ideas or solutions would be much appreciated. 任何想法或解决方案将不胜感激。

I have a generic function I use for such tasks in my CRUD functions 我在CRUD函数中有一个用于此类任务的通用函数

private T SetNullStringToDefault<T>(T entity, string default)
{
    List<PropertyInfo> properties = entity.GetType().GetProperties().ToList();
    foreach(var property in properties)
    {
        //if property is string
        if(property.PropertyType == typeof(string))
        {
            string value = property.GetValue(entity, null) as string;
            if (string.IsNullOrEmpty(value))
                property.SetValue(entity, default, null);
        }
    }
    return entity;
}

And just call it before your insert like 然后在插入之前先调用它

your_object = SetNullStringToDefault<EntityType>(your_object, "Default Value");

Just pass it your object, it will convert all your NULL string properties to your default value. 只要将其传递给您的对象,它将所有NULL字符串属性转换为默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM