Is there an option to make Entity Framework revert empty strings to null?

后端 未结 8 1061
时光说笑
时光说笑 2021-02-06 09:30

I am using an ADO.NET Entity-Framework ObjectContext to access my data store.

I want the if values are set with empty strings, they should automatically become null.

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-06 09:58

    I used Shimmy's solution and was pleased until I discovered that strings in my complex types were being missed. In other words, I needed a way to null out nullable whitespace-only strings in not only my core object/record, but any of its non-primitive object properties, and theirs, and theirs...

    Following is my recursive adaptation. I can't speak to its elegance or production quality because it hasn't been live for very long, but it appears to be working for me so far and may at least serve as a starting point for someone else.

    using System.Data.Entity;
    using System.Data.Entity.Core.Metadata.Edm;
    using System.Data.Entity.Core.Objects;
    using System.Data.Entity.Infrastructure;
    using System.Linq;
    
    public class MyDataContext : DbContext
    {
        public override int SaveChanges()
        {
            ObjectStateEntry[] savingObjectStateEntries = ((IObjectContextAdapter)this)
                .ObjectContext.ObjectStateManager
                .GetObjectStateEntries(EntityState.Added | EntityState.Modified).ToArray();
            foreach (ObjectStateEntry savingObjectStateEntry in savingObjectStateEntries)
                SetEmptyStringsToNull(savingObjectStateEntry.CurrentValues);
    
            return base.SaveChanges();
        }
    
        private static void SetEmptyStringsToNull(CurrentValueRecord currentValueRecord)
        {
            if (currentValueRecord != null)
                for (int i = 0; i < currentValueRecord.FieldCount; i++)
                    if (currentValueRecord[i] is CurrentValueRecord)
                        SetEmptyStringsToNull(currentValueRecord[i] as CurrentValueRecord);
                    else if ((currentValueRecord[i] is string)
                        && (currentValueRecord.DataRecordInfo.FieldMetadata[i].FieldType as EdmProperty).Nullable
                        && string.IsNullOrWhiteSpace(currentValueRecord[i] as string))
                        currentValueRecord.SetValue(i, null);
        }
    }
    

提交回复
热议问题