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:
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. See a screen of debug:
Where is the mistake?
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
... – Aluan Haddad Jul 21 '19 at 10:46