0

保存具有尚未显式设置为空字符串的字符串属性的对象时,LINQ to SQL 将尝试使用 NULL 值插入此记录。

我同意这是它应该如何工作的。但是,对于我正在写入的特定数据库,我想全局覆盖此功能以始终保存一个空字符串。

这可能吗?

4

1 回答 1

4

你需要这样的东西:

public partial class NorthwindDataContext
{
    public override void SubmitChanges(ConflictMode failureMode)
    {
        this.EmptyNullProperties();

        base.SubmitChanges(failureMode);
    }

    private void EmptyNullProperties()
    {
        var propertiesToEmpty =
            from entity in this.GetChangeSet().Inserts
            from property in entity.GetType().GetProperties()
            where property.CanRead && property.CanWrite
            where property.PropertyType == typeof(string)
            where property.GetValue(entity) == null
            select new { entity, property };

        foreach (var pair in propertiesToEmpty)
        {
            pair.property.SetValue(pair.entity, string.Empty);
        }
    }
} 
于 2013-11-11T21:51:51.420 回答