【发布时间】: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