当我只使用实体框架更新列字段时,我需要帮助来理解为什么会收到此消息。
操作失败:无法更改关系,因为一个或多个外键属性不可为空。当对关系进行更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。
我永远不会更新模型中的外键,只会更新一个整数字段来计算每页的视图。
这是我的代码:
// 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;
}
}
感谢您的帮助。在这一个,我不知道从哪里开始......
卡琳
答案 0 :(得分:0)
我觉得你差点太过分了。如果我理解你正确,你要做的事应该很简单:
// 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();
}