SQLite+EF+Codefirst,已有数据表中添加一个not null的列,怎么设置默认值

张天星 2018-11-06 06:29:35
SQL logic error Cannot add a NOT NULL column with default value NULL
大概可以知道原因,一个已经有数据的表,突然加入一个列,这个列中的值自然就是null。
可是我列的属性设置了不允许为空,如int等,如果不加?就是默认必填的。
这时候,我应该怎么在已有数据中加入默认数据?
。。。
我现在的处理是将int改成允许为null,也就是int?,可这只是临时解决方案。
有办法对已有数据填入默认值么。通过C#代码的方式,而不是直接操作数据库。
...全文
233 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
张天星 2018-11-07
  • 打赏
  • 举报
回复
引用 1 楼 daixf_csdn 的回复:
建立basemodel
public class BaseModel
{
/// <summary>
/// 行状态
/// </summary>
[Display(Name = "行状态", AutoGenerateField = false)]
public TrackingState TrackingState { get; set; }

/// <summary>
/// 构造方法
/// </summary>
protected BaseModel()
{
//设置修改跟踪默认状态
TrackingState = Core.TrackingState.NoChange;

//获得属性,根据DefaultValueAttribute设置默认值
Type modelType = this.GetType();
PropertyInfo[] properties = modelType.GetProperties();
foreach (var property in properties)
{
//取得DefaultValueAttribute
object[] attributes = property.GetCustomAttributes(typeof(DefaultValueAttribute), false);
if (attributes != null && attributes.Count() > 0)
{
var attrib = (DefaultValueAttribute)attributes[0];
this.SetPropertyValue(property.Name, attrib.Value);
}
}
}


建立一个类,继承自basemodel,并配置特性DefaultValue
public partial class ass_ba_itemVm : BaseModel
{
///<summary>
///资产Id
///</summary>
[Key, Required]
[Display(Name = "资产Id")]
public long ItemId { get; set; }

///<summary>
///状态{1 有效 / 0 无效}
///</summary>
[Required, StringLength(20)]
[Display(Name = "状态")]
[DefaultValue("1")] //此默认值1111111111111111111111111
public string Status { get; set; }
}


然后你就可以new这个类了。

没用过[DefaultValue("1")] ,我之前默认值都是直接在Model的构造方法里面赋值的,如Status =1;
你这种写法看不是很懂,今晚拷贝下来试试。
圣殿骑士18 2018-11-07
  • 打赏
  • 举报
回复
建立basemodel
public class BaseModel
{
/// <summary>
/// 行状态
/// </summary>
[Display(Name = "行状态", AutoGenerateField = false)]
public TrackingState TrackingState { get; set; }

/// <summary>
/// 构造方法
/// </summary>
protected BaseModel()
{
//设置修改跟踪默认状态
TrackingState = Core.TrackingState.NoChange;

//获得属性,根据DefaultValueAttribute设置默认值
Type modelType = this.GetType();
PropertyInfo[] properties = modelType.GetProperties();
foreach (var property in properties)
{
//取得DefaultValueAttribute
object[] attributes = property.GetCustomAttributes(typeof(DefaultValueAttribute), false);
if (attributes != null && attributes.Count() > 0)
{
var attrib = (DefaultValueAttribute)attributes[0];
this.SetPropertyValue(property.Name, attrib.Value);
}
}
}


建立一个类,继承自basemodel,并配置特性DefaultValue
public partial class ass_ba_itemVm : BaseModel
{
///<summary>
///资产Id
///</summary>
[Key, Required]
[Display(Name = "资产Id")]
public long ItemId { get; set; }

///<summary>
///状态{1 有效 / 0 无效}
///</summary>
[Required, StringLength(20)]
[Display(Name = "状态")]
[DefaultValue("1")] //此默认值1111111111111111111111111
public string Status { get; set; }
}


然后你就可以new这个类了。

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧