【发布时间】:2019-07-11 12:22:00
【问题描述】:
我正在尝试将数据插入到具有大量 not null 约束的 SQL Server 表中:
CREATE TABLE [dbo].[Customer]
(
[CustomerId] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](255) NOT NULL,
[LastName] [varchar](255) NOT NULL,
[AddressLine] [varchar](255) NOT NULL
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED ([CustomerId] ASC)
)
EF 代码:
public virtual DbSet<Customer> Customer { get; set; }
modelBuilder.Entity<Customer>(entity =>
{
entity.Property(e => e.FirstName)
.HasMaxLength(255)
.IsRequired()
.IsUnicode(false);
entity.Property(e => e.LastName)
.HasMaxLength(255)
.IsRequired()
.IsUnicode(false);
entity.Property(e => e.AddressLine)
.HasMaxLength(255)
.IsRequired()
.IsUnicode(false);
});
尝试向表中添加数据时,代码缺少列,因此无法插入到数据库中。不知道这一点,也没有收到“NOT NULL”错误,就像我在 SQL 数据库中看到的那样。
var source = new Customer();
source.FirstName = "Joe"; // missing Last Name and Address
_context.Customer.Add(source);
所以我添加了以下代码。这解决了这个问题,但是我如何让它在任何数据库错误、并发、错误数据类型等上失败。
try
{
_context.SaveChanges();
}
catch (DbUpdateException e)
{
}
以下操作无效: 方法 1 和 2:实现这些后,not null 错误不再如我们所愿出现。
try
{
_context.SaveChanges();
}
catch (Exception e)
{
}
try
{
_context.SaveChanges();
}
catch
{
}
【问题讨论】:
标签: c# entity-framework error-handling .net-core .net-core-2.0