EF Core insert null value to nullable column that has default value

拈花ヽ惹草 提交于 2019-12-11 03:08:58

问题


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())

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

public Guid? SomeId { get; set; }

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.

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 ?

EDIT: To elaborate more

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

    string Name { get; set; }

    Guid? SomeId { get; set; }
}

In Seed method for example:

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

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.


回答1:


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


来源:https://stackoverflow.com/questions/41969303/ef-core-insert-null-value-to-nullable-column-that-has-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!