【问题标题】:How i can say EF6 not insert NULL value我怎么能说 EF6 不插入 NULL 值
【发布时间】:2016-08-17 10:28:32
【问题描述】:

我在迁移中设置了默认值

AlterColumn("Users", "NotNullValue", c => c.String(nullable: false, defaultValue: "Work it!"));

然后我尝试添加新对象,SqlProfiler 显示查询

INSERT [dbo].[WowTable]([NotNullValue],[OnceMoreValue]) VALUES (NULL, 'val')

抛出“无法将 null 值插入列”

当它为空时,有什么方法可以停止插入和更新属性?

更新: 领域类:

public class User 
{
    public string NotNullValue { get; set; }
    public int Id { get; set; }
    public string OnceMoreValue { get; set; }        
}

更新方法:

  public Task AddOrUpdate<TEntity>(TEntity entity) where TEntity : class, IEntity
    {
        _dbContext.Set<TEntity>().AddOrUpdate(x => x.Id, entity);
        return _dbContext.SaveChangesAsync();
    }

调用:

AddOrUpdate(new User{OnceMoreValue = "val"});

【问题讨论】:

  • this。您不能使字符串不可为空。

标签: c# .net entity-framework entity-framework-6


【解决方案1】:

您可以使用 NotNullValue 属性的 [Required] 属性验证模型:

public class User 
{
[Required]
public string NotNullValue { get; set; }
public int Id { get; set; }
public string OnceMoreValue { get; set; }        
}

参考:https://msdn.microsoft.com/en-in/data/gg193959.aspx

或者根据我在您的迁移脚本中看到的,您有此属性的默认值(“Work It”)。因此,在您的 User 类构造函数中,您可以设置 NotNullvalue = "Work It" 以便在您提到的情况下保存此默认值:

AddOrUpdate(new User{OnceMoreValue = "val"});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    相关资源
    最近更新 更多