实体框架所需字段不接受空格



我有一个简单的SQL Server表:

CREATE TABLE [dbo].[Table3]
(
    [PK] [int] NOT NULL DEFAULT ((0)),
    [field1] [varchar](50) NOT NULL DEFAULT (' '),
    [field2] [varchar](1) NOT NULL DEFAULT (' '), 
    CONSTRAINT [Table3_PrimaryKey] PRIMARY KEY CLUSTERED([PK] ASC) ON [PRIMARY]
) ON [PRIMARY] 

在SQL Server中,下列查询是有效的:

   INSERT INTO Table3
   VALUES (1, 'Test1', ' ')
   INSERT INTO Table3
   VALUES (2, 'Test2', '')
   INSERT INTO Table3 (PK, field1)
   VALUES (3, 'Test3')
   INSERT INTO Table3
   VALUES (4, 'Test4', 'X')

我首先用实体框架6代码创建了一个控制台应用程序。当我尝试添加新记录时,插入失败,出现"必填字段"错误。空格似乎对field2无效,但在SQL中是合法的。

using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
  class Program
  {
      static void Main(string[] args)
      {
          try
          {
            using (Model1 ctx = new Model1())
            {
                ctx.Database.Log = Console.WriteLine;
                Table3 t3 = new Table3();
                t3.PK = 1;
                t3.field1 = "Test";
                t3.field2 = " ";
                ctx.Table3.Add(t3);
                ctx.SaveChanges();
            }
          }
          catch (System.Data.Entity.Validation.DbEntityValidationException ex)
          {
              Console.Write(ex.Message);
          }
          catch (Exception ex)
          {
              Console.Write(ex.Message);
          }
      }
  }
}

模型
namespace ConsoleApplication2
{
  using System;
  using System.Data.Entity;
  using System.ComponentModel.DataAnnotations.Schema;
  using System.Linq;
  public partial class Model1 : DbContext
  {
    public Model1()
        : base("name=Model11")
    {
    }
    public virtual DbSet<Table3> Table3 { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Table3>()
            .Property(e => e.field1)
            .IsUnicode(false);
        modelBuilder.Entity<Table3>()
            .Property(e => e.field2)
            .IsUnicode(false);
    }
  }
}

namespace ConsoleApplication2
{
  using System;
  using System.Collections.Generic;
  using System.ComponentModel.DataAnnotations;
  using System.ComponentModel.DataAnnotations.Schema;
  using System.Data.Entity.Spatial;
  public partial class Table3
  {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int PK { get; set; }
    [Required]
    [StringLength(50)]
    public string field1 { get; set; }
    [Required]
    [StringLength(1)]
    public string field2 { get; set; }
  }
}

谢谢米歇尔。

我知道这是一个老帖子。我今天也遇到了类似的问题。我发现添加[Required(AllowEmptyStrings = true)]有帮助。

最新更新