1
我需要幫助來理解爲什麼當我僅用實體框架更新列字段時,爲什麼會收到此消息。更新一個列字段會產生一個關係錯誤
操作失敗:無法更改關係,因爲一個或多個外鍵屬性是不可空的。當對關係進行更改時,相關的外鍵屬性將設置爲空值。如果外鍵不支持空值,則必須定義新的關係,必須爲外鍵屬性指定另一個非空值,或者必須刪除不相關的對象。
我從來不更新我的模型中的外鍵,但只有一個整數字段來計算每頁的視圖。
這裏是我的代碼:
// 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;
}
}
謝謝您的幫助。就這一個,我不知道從哪裏開始..
卡林納