SQL logic error Cannot add a NOT NULL column with default value NULL
大概可以知道原因,一个已经有数据的表,突然加入一个列,这个列中的值自然就是null。
可是我列的属性设置了不允许为空,如int等,如果不加?就是默认必填的。
这时候,我应该怎么在已有数据中加入默认数据?

我现在的处理是将int改成允许为null,也就是int?,可这只是临时解决方案。
有办法对已有数据填入默认值么。通过C#代码的方式,而不是直接操作数据库。

解决方案 »

  1.   

    建立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这个类了。
      

  2.   

    没用过[DefaultValue("1")] ,我之前默认值都是直接在Model的构造方法里面赋值的,如Status =1;
    你这种写法看不是很懂,今晚拷贝下来试试。