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)
任何帮助都将非常感激.
您必须将外键属性设置为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)