EF Core无法将null值插入具有默认值的列中

编程入门 行业动态 更新时间:2024-10-22 10:59:19
本文介绍了EF Core无法将null值插入具有默认值的列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有实体

public class Realtor { [Key] public int Id { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Guid { get; set; } public string FirstName { get; set; } public string LastName { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public DateTime Registration { get; set; } [ForeignKey("Id")] public int SubdivId { get; set; } public Subdiv Subdiv { get; set; } }

以及使用OnModelCreating方法的上下文

and context with OnModelCreating method

modelBuilder.Entity<Realtor>(real => { real.Property<Guid>(p => p.Guid) .HasDefaultValueSql("newsequentialid()"); real.Property<DateTime>(p => p.Registration) .HasDefaultValueSql("getdate()"); real.HasOne(r => r.Subdiv) .WithMany(s => s.Realtors) .HasForeignKey(r => r.SubdivId); });

我为属性注册设置了默认值,但是当我执行插入操作时,出现异常:无法插入

I set default value for property Registration, but when I do an insert, I get Exception: cannot insert the value null into column Registration.

推荐答案

首先,删除 [DatabaseGenerated(DatabaseGeneratedOption.Identity )] 表示 Restration 。这可能是导致您异常的原因。如果您不想使其成为可空值并希望通过您的实体设置该值,则还可以:

First of all, remove the [DatabaseGenerated(DatabaseGeneratedOption.Identity)] for Restration. This could be the cause for your exception. If you don't want to make it nullable and want to set the value with your entity you could also:

public DateTime Restration { get; set; } = DateTime.Now;

应该工作(我这里没有VS 2015,所以您必须测试。否则进行设置

Should work (I ain't got a VS 2015 here, so you have to test. Otherwise set the value for Restration in constructor.)

update: 和至少删除此行

update: and remove at least this line

real.Property<DateTime>(p => p.Registration) .HasDefaultValueSql("getdate()");

更多推荐

EF Core无法将null值插入具有默认值的列中

本文发布于:2023-11-16 01:36:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1599810.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:默认值   EF   Core   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!