简体   繁体   English

Npgsql,保存DateTime值期间出错(“ CreatedAt”列中的空值违反了非空约束)

[英]Npgsql, error during saving a DateTime value (null value in column “CreatedAt” violates not-null constraint)

I have the following model: 我有以下模型:

public class Product
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public string Category { get; set; }

    public decimal Price { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    [ScaffoldColumn(false)]
    public DateTime CreatedAt { get; set; } = DateTime.Now;
}

And the following application context: 以及以下应用程序上下文:

public class ApplicationContext : DbContext
{
    private readonly string _connectionString;

    public DbSet<Product> Products { get; set; }

    public ApplicationContext(IConfiguration configuration)
    {
        _connectionString = configuration.GetConnectionString("Sportshop");
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql(_connectionString, b => b.MigrationsAssembly("Web"));
    }
}

Next I will show you a screen of my PostgreSQL data base schema: 接下来,我将向您显示PostgreSQL数据库模式的屏幕:

在此处输入图片说明

I'm trying to save a new entity with the help of the next code: 我正在尝试在下一个代码的帮助下保存一个新实体:

    public ViewResult Index()
    {
        Product product = new Product
        {
            Name = "P1",
            Category = "test",
            Price = 1000,
            Description = "Hello !!!"
        };

        _applicationContext.Products.Add(product);
        _applicationContext.SaveChanges();


        return View(// ... some view data);
    }

But as the result I see this error. 但是结果我看到了这个错误。 I don't understand why. 我不明白为什么。

在此处输入图片说明

I absolutely sure that CreatedAt field is not null during the saving. 我绝对确定在保存期间CreatedAt字段不为null。 See a screen of debug: 看到调试屏幕:

在此处输入图片说明

Where is the mistake? 错误在哪里?

Your property indeed has a value, but it is also decorated with [DatabaseGenerated(DatabaseGeneratedOption.Computed)] . 您的属性确实有一个值,但也用[DatabaseGenerated(DatabaseGeneratedOption.Computed)]装饰。

By using Computed , you are telling EF Core that it must leave the property's value upto the database. 通过使用Computed ,您将告诉EF Core必须将属性的值保留给数据库。 In other words, the database is made fully responsible for generating or computing a value during every query. 换句话说,使数据库完全负责在每次查询期间生成或计算值。 As can be read here , " The practical effect of this is that Entity Framework will not include the property in INSERT or UPDATE statements ". 可以在这里阅读,“ 这的实际效果是Entity Framework将不会在INSERT或UPDATE语句中包括该属性 ”。

The generated insert statement will then look like 生成的插入语句将如下所示

INSERT INTO Products (Id, Name, Description, Category, Price) ...

Which will fail because CreatedAt has a NOT NULL setting, apparently without a default value. 由于CreatedAt具有NOT NULL设置(显然没有默认值),因此将失败。

You can try giving the field a default value using the Fluent API : 您可以尝试使用Fluent API为该字段提供默认值

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>()
        .Property(b => b.CreatedAt)
        .HasDefaultValueSql("getdate()");
}

This should work as long as it is supported for Npgsql, which I don't know for sure. 只要Npgsql支持它,它就应该起作用,我不确定。 If it does not work then you may have no other option but to remove the attribute and take value creation in your own hands. 如果它不起作用,那么您可能别无选择,只能删除该属性并自己掌控价值创造。

暂无
暂无

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

相关问题 EF WPF-“ ContractID”列中的空值违反了非空约束 - EF WPF - null value in column “ContractID” violates not-null constraint 如果EF PostgreSQL在“ ReportId”列(Pimary键)中抛出空值,则如何使用EF PostgreSQL违反了非空约束 - How to work with EF PostgreSQL if it throw null value in column “ReportId” (Pimary key) violates not-null constraint 值出现在非空约束列中,但Postgres抛出异常 - Value present in not-null constraint column but Postgres throws Exception 从NpgSQL加载空值时出现DataTable约束错误 - DataTable constraint error when loading null value from NpgSQL 具有非空约束的ODBC postgres错误 - ODBC postgres error with not-null constraint not-null属性引用一个null或瞬态值 - not-null property references a null or transient value Nhibernate:not-null属性以多对一关系引用null或瞬态值错误 - Nhibernate : not-null property references a null or transient value error in many to one relationship 我的nhibernate映射不应该解决这个问题吗? 错误:not-null属性引用null或transient值 - Shouldn't my nhibernate mapping take care of this? Error: not-null property reference a null or transient value NHibernate - not-null属性引用null或transient值 - NHibernate - not-null property reference a null or transient value not-null属性引用的是null或瞬态值-了解Inverse和Cascade - not-null property references a null or transient value - understanding of Inverse and Cascade
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM