1

说我有这门课:

public class BuzzKill
{
public string Name {get;set;}
public DateTime? StrikeDate {get;set;}
}

如果我将此类的实例写入具有 null 的数据库StrikeDate,然后尝试使用以下方法更新并保存它(取自 Julia Lehrman 的书DbContext),我会收到以下异常:

System.InvalidOperationException : The original value for the property 'StrikeDate' cannot be set to null because the 'StrikeDate' member on the entity type 'BuzzKill' is not nullable.

显然,该成员可以为空。有没有人有解决方法或解决方案?我正在使用 EF 5.0。

这是我用来更新实体的代码,以及一条注释,指出异常被抛出的位置:

 public virtual void ApplyChanges<TEntity>(TEntity root)
            where TEntity : class, IObjectWithState
        {
            using (var context = new AmazingChartsContext())
            {
                context.Set<TEntity>().Add(root);

                CheckForEntitiesWithoutStateInterface(context);

                foreach (var entry in context.ChangeTracker.Entries<IObjectWithState>())
                {
                    IObjectWithState stateInfo = entry.Entity;
                    entry.State = ConvertState(stateInfo.State);
                    if (stateInfo.State == State.Unchanged)
                    {                           
                        ApplyPropertyChanges(entry.OriginalValues, stateInfo.OriginalValues);
                    }
                }

                try
                {
                    context.SaveChanges();
                }
                catch (DbEntityValidationException ex)
                {
                   //stuff...

                }
            }
        }

        protected void ApplyPropertyChanges(DbPropertyValues values, Dictionary<string, object> originalValues)
        {
            foreach (var originalValue in originalValues)
            {
                if (originalValue.Value is Dictionary<string, object>)
                {
                    ApplyPropertyChanges((DbPropertyValues)values[originalValue.Key],
                        (Dictionary<string, object>)originalValue.Value);
                }
                else
                {
                    values[originalValue.Key] = originalValue.Value; //here's where the exception gets thrown
                }
            }
        }

(我在这里读到了这个问题,但除了这是 4.3 中的一个错误之外,似乎没有人有答案。)

4

0 回答 0