使用Entity Framework Core覆盖插入的sql默认值(7) [英] Override sql default value on insert using Entity Framework Core (7)

查看:171
本文介绍了使用Entity Framework Core覆盖插入的sql默认值(7)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,其中列有[CreatedAtIsoUtc],设置Sql Server默认值

I have a table with a column [CreatedAtIsoUtc] that sets a Sql Server default value

migrationBuilder.CreateTable(
            name: "CurrentAccountLedger",
            columns: table => new
            {
                Id = table.Column<Guid>(nullable: false, defaultValueSql: "newsequentialid()"),
                CreatedAtIsoUtc = table.Column<DateTime>(nullable: false, defaultValueSql: "GETUTCDATE()"),                    
            }

        });

在原始的sql server查询中,我可以插入一个记录并覆盖[CreatedAtIsoUtc]默认值。

In a raw sql server query, I can insert a record and overwrite the [CreatedAtIsoUtc] default value.

在实体框架中,执行Add()操作时,似乎不能覆盖此值。

In Entity Framework, I can't seem to overwrite this value when performing an Add() operation.

任何关于我如何使这个工作的想法?

Any ideas on how I could get this working?

推荐答案

实际上在EF Core v1.1.0中,你可以通过设置属性与类型的默认值不同(即 0 的数字 false for bool null for string 和可空类型,在您的情况下 default(DateTime))。唯一的当前限制是您不能用 0 false 覆盖sql默认值null 等。

Actually in EF Core v1.1.0 you can do that by setting the property to any value different than the default for the type (i.e. 0 for numbers, false for bool, null for string and nullable types, default(DateTime) in your case). The only current limitation is that you cannot override the sql default value with 0, false, null etc.

例如

db.CurrentAccountLedger.Add(new CurrentAccountLedger { });

将使用 CreatedAtIsoUtc 等于默认的 GETUTCDATE(),而

db.CurrentAccountLedger.Add(new CurrentAccountLedger { CreatedAtIsoUtc = new DateTime(2017, 1, 1) });

将插入具有指定值的记录。

would insert a record with the specified value.

这篇关于使用Entity Framework Core覆盖插入的sql默认值(7)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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