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

jal*_*len 5 entity-framework-4

我无法将我的Entity Framework 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!!!
Run Code Online (Sandbox Code Playgroud)

任何帮助都将非常感激.

Sla*_*uma 9

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

account.CorporationId = null;

db.Entry(account).State = EntityState.Modified;
db.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

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

var account = db.Account.Include(a => a.Corporation)
    .Where(a => a.Id == accountId)
    .SingleOrDefault();

if (account != null)
{
    account.Corporation = null;
    db.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)

  • @Slauma,感谢您的回答 - 我在将关联属性设置为 null 时遇到问题,并使用 .Include() 解决了问题。您能否解释一下,当我们所做的只是将关联属性设置为 null 时,为什么需要 .Include() 关联属性?抱歉挖出一个老话题。 (2认同)