Core将空值插入具有默认值的可空列

Core将空值插入具有默认值的可空列

本文介绍了EF Core将空值插入具有默认值的可空列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用EF Core时,我对SQL中的特定场景感到好奇。
例如,有一个列允许null,同时具有defalut值,这是不寻常的情况,但这不是这里的问题。
问题是关于技术的可能性。

I am curious about specific scenario in SQL when using EF Core.For example there is a column that allows null and at the same time has defalut value, it is unusual situation but that is not the issue here.Question is about technical possibility.

[SomeId] [uniqueidentifier] NULL DEFAULT (newsequentialid())

在应用程序中有Entity(Code First)具有适当的属性

And in Application there is Entity(Code First) which has appropriate Property

public Guid? SomeId { get; set; }

问题是如何将此实体插入数据库,以便 SomeId 将具有Null值。因为即使属性为Null,数据库也会用默认值覆盖它。

The problem is how to Insert this Entity into DB so that SomeId would have Null value. Because even when property is Null, Database will override it with default value.

这可以通过明确的将null分配给列来完成纯sql,但是似乎也可以不能用EF完成,还是我错了?

This can be done with pure sql by explicitly assigning null to column but it seems that the same can't be done with EF, or am I wrong ?

编辑:
详细说明

To elaborate more

public class ExampleTable
{
    [Key]
    int Id { get; set; }

    string Name { get; set; }

    Guid? SomeId { get; set; }
}

在种子方法中,例如:

var record1 = new ExampleTable
{
    FirstName = "Carson"
}
var record2 = new ExampleTable
{
    FirstName = "Carson",
    SomeId = null
}
context.ExampleTableSet.Add(record1);
context.ExampleTableSet.Add(record2);
context.SaveChanges(record);

记录1和2是相同的,因为SomeId 是可空的Guid?并且在两个案例中,在数据库中提交 SomeId 后,可以从 newsequentialid 获取真实值。
有没有办法让数据库中的 SomeId 空。

record 1 and 2 are the same since SomeId is nullable Guid?, and in both cases after Submiting SomeId in database gets real value from newsequentialid.Is there any way to keep SomeId Null in database as well.

推荐答案

'我不知道我是否完全理解这个问题,但是通过修改你的声明你可以设置默认值。创建记录时,SomeId将默认为 NULL

I'm not sure if I understand the question fully, but by modifying your declaration you can set the default value. On creation of a record, 'SomeId' will default to NULL

    public class ExampleTable
    {
        public ExampleTable()
        {
            SomeId = null;
        }

        public Guid? SomeId { get; set; }
    }

这篇关于EF Core将空值插入具有默认值的可空列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:49