实体框架不会将外键值更新为 null



我无法将实体框架 4.3 代码优先数据库中的外键更新为 null。

我的视图模型:

public class AccountViewModel
{
    public int Id { get; set; }
    public int? CorporationId { get; set; } 
    public CorporationModel Corporation { get; set; }
}
var corporation = db.Corporation.Where(x => x.Id == model.CorporationId).FirstOrDefault();  // shows as null
account.Corporation = corporation;  // sets the value to null
db.Entry(account).State = EntityState.Modified;
db.SaveChanges();  // does not save the null value in the FK field!!!

任何帮助将不胜感激。

必须将外键属性设置为 null 。将状态设置为 Modified 仅影响标量属性(外键属性是其中之一,但不是导航属性):

account.CorporationId = null;
db.Entry(account).State = EntityState.Modified;
db.SaveChanges();

如果Account上没有外键属性,则必须加载包括公司在内的帐户:

var account = db.Account.Include(a => a.Corporation)
    .Where(a => a.Id == accountId)
    .SingleOrDefault();
if (account != null)
{
    account.Corporation = null;
    db.SaveChanges();
}

最新更新