是否有一个选项可以使实体框架将空字符串恢复为 null?

发布于 2024-07-27 00:39:45 字数 97 浏览 5 评论 0原文

我正在使用 ADO.NET Entity-Framework ObjectContext 来访问我的数据存储。

我希望如果值设置为空字符串,它们应该自动变为空。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

秋日私语 2024-08-03 00:39:45

如果您使用 Entity Framework 4,则可以使用 T4 模板来完成此操作。 只需将其放在 .tt 模板文件中每个字符串属性的 getter 中,它就会用 null 替换空字符串并自动修剪字符串。 无需使用反射。

<#+ if (primitiveProperty.TypeUsage.ToString().Split('.').Last() == "String") { #>
   if (value == "") value = null;
   else value = value.Trim();
<#+ } #>

If your using Entity Framework 4, you can use T4 templates to accomplish this. Just place this in the getter of each string property in your .tt template file, and it will replace empty strings with null and automatically trim strings. No need to use reflection.

<#+ if (primitiveProperty.TypeUsage.ToString().Split('.').Last() == "String") { #>
   if (value == "") value = null;
   else value = value.Trim();
<#+ } #>
朦胧时间 2024-08-03 00:39:45

我实际上找到了一种更好的方法,它实际上是内置在系统中的,而且它使用无论如何加载的实体的内部序数元数据(我还没有测试性能差异,但这应该比反射):

private const string StringType = "String";
private const EntityState SavingState = EntityState.Added | EntityState.Modified;
public override int SaveChanges()
{
  //when using on ObjectContext replace 'objectContext' with 'this',
  //and override SaveChanges(SaveOptions options) instead:

  var objectContext = ((IObjectContextAdapter)this).ObjectContext;
  var savingEntries = objectContext.ObjectStateManager
    .GetObjectStateEntries(SavingState);

  foreach (var entry in savingEntries)
  {
    var curValues = entry.CurrentValues;
    var fieldMetadata = curValues.DataRecordInfo.FieldMetadata;
    var stringFields = fieldMetadata
      .Where(f => f.FieldType.TypeUsage.EdmType.Name == StringType);
    foreach (var stringField in stringFields)
    {
      var ordinal = stringField.Ordinal;
      var curValue = curValues[ordinal] as string;
      if (curValue != null && curValue.All(char.IsWhiteSpace))
        curValues.SetValue(ordinal, null);
    }
  }
  return base.SaveChanges(); //SaveChanges(options) on ObjectContext
}

I actually found a better way to this, it's actually built in the system, plus it uses the internal ordinal metadata of the entities which are loaded anyway (I haven't tested the performance difference, but this should be hell of a lot faster than reflection):

private const string StringType = "String";
private const EntityState SavingState = EntityState.Added | EntityState.Modified;
public override int SaveChanges()
{
  //when using on ObjectContext replace 'objectContext' with 'this',
  //and override SaveChanges(SaveOptions options) instead:

  var objectContext = ((IObjectContextAdapter)this).ObjectContext;
  var savingEntries = objectContext.ObjectStateManager
    .GetObjectStateEntries(SavingState);

  foreach (var entry in savingEntries)
  {
    var curValues = entry.CurrentValues;
    var fieldMetadata = curValues.DataRecordInfo.FieldMetadata;
    var stringFields = fieldMetadata
      .Where(f => f.FieldType.TypeUsage.EdmType.Name == StringType);
    foreach (var stringField in stringFields)
    {
      var ordinal = stringField.Ordinal;
      var curValue = curValues[ordinal] as string;
      if (curValue != null && curValue.All(char.IsWhiteSpace))
        curValues.SetValue(ordinal, null);
    }
  }
  return base.SaveChanges(); //SaveChanges(options) on ObjectContext
}
秋叶绚丽 2024-08-03 00:39:45

我刚刚将上面的代码改编为新版本的 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();

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();
压抑⊿情绪 2024-08-03 00:39:45

据我所知。

您可以编写一个继承自 ObjectContext 的类并重写 SaveChanges() 来执行此操作,并在 x.objectlayer 中使用它而不是 ObjectContext .cs/x.designer.cs

Not that I'm aware of.

You could possibly write a class that inherited from ObjectContext and override SaveChanges() to do that and use that instead of ObjectContext in your x.objectlayer.cs / x.designer.cs

别念他 2024-08-03 00:39:45

我没有通过覆盖 ObjectContext 让事情变得复杂,而是使用字符串扩展方法来转换数据库存储的值

public static class StringExtensions
{
    public static string EmptyStringToNull(this string s)
    {
        return string.IsNullOrWhiteSpace(s) ? null : s;
    }

    public static object EmptyStringToDBNull(this string s)
    {
        if (string.IsNullOrWhiteSpace(s)) 
            return DBNull.Value;
        else 
            return s;
    }
}

Rather than complicating things by overriding the ObjectContext I use string extension methods to convert values for database storage

public static class StringExtensions
{
    public static string EmptyStringToNull(this string s)
    {
        return string.IsNullOrWhiteSpace(s) ? null : s;
    }

    public static object EmptyStringToDBNull(this string s)
    {
        if (string.IsNullOrWhiteSpace(s)) 
            return DBNull.Value;
        else 
            return s;
    }
}
谈情不如逗狗 2024-08-03 00:39:45

这是 Entity Framework Core 的解决方案(在 V2 中测试)。 由于文档有限,我不得不通过 API 进行尝试,因此可能还有其他方法可以完成同样的事情。 请注意,使用此方法修改了原始对象。

public override int SaveChanges()
{
    ConvertWhitespaceToNulls();
    return base.SaveChanges();
}


private void ConvertWhitespaceToNulls()
{
    var entityEntries = this.ChangeTracker
        .Entries()
        .Where(x => x.State == EntityState.Modified || x.State == EntityState.Added && x.Entity != null);

    foreach (var e in entityEntries)
        foreach (var currentValue in e.CurrentValues.Properties.Where(p => p.ClrType == typeof(string) && p.IsNullable))
            if (string.IsNullOrWhiteSpace((string) currentValue.FieldInfo.GetValue(e.Entity)))
                currentValue.FieldInfo.SetValue(e.Entity, null);
}

Here is a solution for Entity Framework Core (tested in V2). Had to bang my way through the API due to limited documentation so there might be other ways to accomplish the same thing. Note that the original objects are modified using this method.

public override int SaveChanges()
{
    ConvertWhitespaceToNulls();
    return base.SaveChanges();
}


private void ConvertWhitespaceToNulls()
{
    var entityEntries = this.ChangeTracker
        .Entries()
        .Where(x => x.State == EntityState.Modified || x.State == EntityState.Added && x.Entity != null);

    foreach (var e in entityEntries)
        foreach (var currentValue in e.CurrentValues.Properties.Where(p => p.ClrType == typeof(string) && p.IsNullable))
            if (string.IsNullOrWhiteSpace((string) currentValue.FieldInfo.GetValue(e.Entity)))
                currentValue.FieldInfo.SetValue(e.Entity, null);
}
少女七分熟 2024-08-03 00:39:45

为了完整起见,这里是将接受的答案编写为部分类而不是继承类。 请注意,此版本还会修剪字符串。

using System.Data;
using System.Data.Objects;
using System.Linq; 
public partial class MyObjectContext {
    private const string StringType = "String";
    private const EntityState SavingState = EntityState.Added | EntityState.Modified;

    public override int SaveChanges(SaveOptions options) {
        var savingEntries = this.ObjectStateManager.GetObjectStateEntries(SavingState);

        foreach (var entry in savingEntries) {
            var curValues = entry.CurrentValues;
            var fieldMetadata = curValues.DataRecordInfo.FieldMetadata;
            var stringFields = fieldMetadata.Where(f => f.FieldType.TypeUsage
                                                         .EdmType.Name == StringType);

            foreach (var stringField in stringFields) {
                var ordinal = stringField.Ordinal;
                var curValue = curValues[ordinal] as string;

                if (curValue != null && curValue.All(char.IsWhiteSpace)) {
                    curValues.SetValue(ordinal, null);
                }
                else if (curValue != null && curValue != curValue.Trim()) {
                    curValues.SetValue(ordinal, curValue.Trim());
                }
            }
        }
        return base.SaveChanges(options);
    }
}

我还展示了所需的使用,因为当我复制粘贴代码并且 IDE 抛出一些有关未找到类型或命名空间的错误时,我发现这令人沮丧。

Just for completeness, here is the accepted answer written as a partial class instead of inherited. Note that this version also trims strings.

using System.Data;
using System.Data.Objects;
using System.Linq; 
public partial class MyObjectContext {
    private const string StringType = "String";
    private const EntityState SavingState = EntityState.Added | EntityState.Modified;

    public override int SaveChanges(SaveOptions options) {
        var savingEntries = this.ObjectStateManager.GetObjectStateEntries(SavingState);

        foreach (var entry in savingEntries) {
            var curValues = entry.CurrentValues;
            var fieldMetadata = curValues.DataRecordInfo.FieldMetadata;
            var stringFields = fieldMetadata.Where(f => f.FieldType.TypeUsage
                                                         .EdmType.Name == StringType);

            foreach (var stringField in stringFields) {
                var ordinal = stringField.Ordinal;
                var curValue = curValues[ordinal] as string;

                if (curValue != null && curValue.All(char.IsWhiteSpace)) {
                    curValues.SetValue(ordinal, null);
                }
                else if (curValue != null && curValue != curValue.Trim()) {
                    curValues.SetValue(ordinal, curValue.Trim());
                }
            }
        }
        return base.SaveChanges(options);
    }
}

I have also shown the required usings because I find it frustrating when I copy'n'paste code and the IDE throws up some errors about type or namespace not found.

池予 2024-08-03 00:39:45

我使用了 Shimmy 的解决方案并且很高兴,直到我发现我的复杂类型中的字符串被遗漏了。 换句话说,我需要一种方法来不仅在我的核心对象/记录中,而且在它的任何非原始对象属性、他们的属性和他们的属性中清空可空的空白字符串......

以下是我的递归改编。 我无法谈论它的优雅或生产质量,因为它上线的时间不长,但到目前为止它似乎对我有用,并且至少可以作为其他人的起点。

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);
    }
}

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);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文