【问题标题】:Updating one column field generates a relationship bug更新一个列字段会产生关系错误
【发布时间】:2014-02-20 22:40:27
【问题描述】:

我需要帮助来了解为什么我只使用实体框架更新列字段时收到此消息。

操作失败:无法更改关系,因为一个或多个外键属性不可为空。当对关系进行更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。

我从不更新模型中的外键,而只更新一个整数字段,用于计算每页的视图。

这是我的代码:

// Service
...
Tender currentTender = base.GetById(tenderId)
currentTender.ViewCount = currentTender.ViewCount + 1;
base.UpdateSpecificFieldsOnly(currentTender, views => views.ViewCount);

// Repository
        public bool UpdateSpecificFieldsOnly(TEntity entityToUpdate, params Expression<Func<TEntity, object>>[] includeProperties)
        {
            if (entityToUpdate == null)
            {
                throw new ArgumentException("Cannot add a null entity.");
            }

            try
            {
                var id = this.dbSet.Create().GetType().GetProperty("Id").GetValue(entityToUpdate);

                this.dbSet.Attach(entityToUpdate);
                foreach (var includeProperty in includeProperties)
                {
                    context.Entry(entityToUpdate).Property(includeProperty).IsModified = true;
                }

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

public virtual bool Save(bool shouldValidateEntity = true)
        {
            try
            {
                context.Configuration.ValidateOnSaveEnabled = shouldValidateEntity;
                context.SaveChanges();
                return true;
            }
        }

感谢您的帮助。在这个,我不知道从哪里开始..

卡琳

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    我认为你做得太过分了。如果我理解你的话,你想要做的应该很简单:

    // replace "EFDbContext" with your EF context class
    using (var context = new EFDbContext()) 
    {
        // replace "Id" with your primary key column name for tender
        var currentTender = context.Tenders.Single(t => t.Id == tenderId);
        currentTender.ViewCount = currentTender.ViewCount + 1;
        context.SaveChanges(); 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 2011-10-06
      • 1970-01-01
      相关资源
      最近更新 更多