EF Core 始终在
INSERT
语句中包含类的所有列。如何修改脚本,以便 INSERT
语句仅包含我已提供值的值?
假设我有一个具有 3 个属性的 User 类:
public int Id { get; set; } // this one is linked to a auto increment ID column
public string Name { get; set; }
public int Amount { get; set; } // linked to a column that cannot be null and has a default value configured in SQL Server
所以我正在做的向用户表插入一条新记录是:
User newUser = new User();
newUser.Name = "John";
await _dbc.AddAsync(newUser);
await _dbc.SaveChangesAsync();
INSERT
语句将包含Name = "JOHN"
,但也会包含Amount = null
,因此查询将失败,因为 Amount 不接受 null。我想从生成的 Amount
语句中删除 INSERT
列以简单地发送
INSERT INTO User (NAME)
VALUES ('John')
我想让 SQL Server 将默认配置的值插入到
Amount
列中。
这是一个简单的例子,我的实际情况有很多列,我有插入的默认值,并且我不希望生成的
INSERT
语句包含 User
类中的所有列,只包含那些我提供了一个值。
对于不可为空且具有数据库默认值的模型属性,您需要注释或配置该属性以使 EF 了解数据库默认值。
本文演示了两者:https://www.learnentityframeworkcore.com/configuration/fluent-api/valuegenerateonadd-method
使用流畅的配置,您需要添加
ValueGeneratedOnAdd()
。例如:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace YourNamespaceHere
{
public partial class UserConfiguation : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
// ... other field configurations
builder
.Property(m => m.Amount)
.ValueGeneratedOnAdd();
OnConfigurePartial(builder);
}
partial void OnConfigurePartial(EntityTypeBuilder<User> builder);
}
}
作为数据注释,您将使用 DatabaseGeneeratedAttribute:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace YourNamespaceHere
{
[Table(nameof(User))]
public class User
{
// ... other properties
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int Amount { get; set; }
}
}