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

后端 未结 8 1063
时光说笑
时光说笑 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:41

    I've just adapted the code above to the new release of Entity Framework 4.1 (DbContext).

    public override int SaveChanges()
        {
            var objContext = ((IObjectContextAdapter)this).ObjectContext;
            var entries = objContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified).Select(
                    entry => entry.Entity);
            foreach (var entity in entries)
            {
                string str = typeof(string).Name;
                var properties = from p in entity.GetType().GetProperties()
                                 where p.PropertyType.Name == str
                                 select p;
    
                foreach (var item in properties)
                {
                    string value = (string)item.GetValue(entity, null);
                    if (value != null && value.Trim().Length == 0)
                    {
    
                        item.SetValue(entity, null, null);
    
                    }
                }
            }
            return base.SaveChanges();
    

提交回复
热议问题