6

EntityFramework4.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!!!

どんな援助でも大歓迎です。

4

1 に答える 1

11

外部キープロパティをに設定する必要がありますnull。状態をスカラープロパティにのみ影響するように設定しModifiedます(外部キープロパティはそのうちの1つですが、ナビゲーションプロパティには影響しません)。

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();
}
于 2012-06-07T15:50:59.760 に答える