How to save null strings as string.empty when saving changes?
说我有一个像这样的类(为简洁起见,省略了详细信息):
1 2 3 4 5 6 7 8 | public class Address { public Address() { PostalCode =""; } public string PostalCode { get; set; } } |
在映射中,邮政编码被标记为必填项:
1 2 3 4 5 6 7 | public AddressMap() { this.Property(t => t.PostalCode) .HasColumnName("PostalCode") .IsRequired() .HasMaxLength(50); } |
在数据库中定义如下:
1 2 3 | CREATE TABLE [dbo].[Address] ( [PostalCode] VARCHAR (50) NOT NULL DEFAULT (('')) ); |
它在代码中初始化为
的空值
1 2 3 4 5 |
当我将该地址添加到dbContext并保存更改时,得到了
是否有一种使实体框架或数据库不尝试将
一个选项是更改属性的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class Address { private string _postalCode; public Address() { PostalCode =""; } public string PostalCode { get { //This will never return a null return _postalCode ??""; } set { _postalCode = value; } } } |
由于某种原因,答案对我没有用。最有可能是因为某些EF基础设置。
但是,在
[Required(AllowEmptyStrings = true)]
解决了问题。
P.S。我在字符串属性上有
您始终可以遍历类的不同部分,并使用System.Reflection进行nullCheck。这是几个将通用类列表传输到datatable和datatableRow的示例。您可以将相同的想法与GetProperties一起使用以进行空检查,并将类转换为SQL插入,CSV数据,XML或自动需要的任何内容。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public static DataTable create_DataTable_From_Generic_Class(Type t) { DataTable d = new DataTable(); FieldInfo[] fI = t.GetFields(); for(int i = 0; i < fI.Length; i++) { DataColumn dC = new DataColumn(fI[i].Name, fI[i].FieldType); d.Columns.Add(dC); } return d; } public static object[] Create_Datatable_Row_From_Generic_Class(Type t, object instance,DataTable dt) { FieldInfo[] f = t.GetFields(); object[] ret = new object[f.Length]; for (int i = 0; i < dt.Columns.Count; i++) { ret[i] = t.GetField(dt.Columns[i].ColumnName).GetValue(instance); if (ret[i] == null) { ret[i] ="null"; } } return ret; } |
也许可以在调用SaveChanges()之前在上下文类中设置Configuration.ValidateOnSaveEnabled = false。
1 2 | context.Configuration.ValidateOnSaveEnabled = false; context.SaveChanges(); |
实体框架/ MVC3:暂时禁用验证
为什么将String初始化为null?如果您使用,可能是:
1 2 3 |
如果要确保永远都不为空,可以使用@DavidG的解决方案,但如果要检查何时为null,则只需初始化为String.Empty