簡體   English   中英

實體框架SaveChanges錯誤

[英]Entity Framework SaveChanges bug

我不太確定這是否是錯誤,但對我來說很像。 我首先使用Entity Framework 6.1.1代碼,並且具有以下類:

public class User
{
    public int Id { get; set; }
    [Required]
    [MaxLength(20)]
    public string Username { get; set; }
    [Required]
    [MaxLength(200)]
    public string Password { get; set; }
    [Required]
    public virtual Country Country { get; set; }

}

public class Country
{
    [Key]
    public int Id { get; set; }
    [Required]
    [MaxLength(3)]
    public string CountryCode { get; set; }
    [Required]
    [MaxLength(20)]
    public string CountryName { get; set; }
}

當我嘗試使用以下代碼更新用戶密碼時,出現錯誤:

User _user = db.Users.Find(Id);
_user.Password = Password;
db.Entry(_user).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();

錯誤:一個或多個實體的驗證失敗。 有關更多詳細信息,請參見'EntityValidationErrors'屬性。 驗證錯誤是:“國家/地區”字段為必填項。“}

關鍵是,如果我與_user.Country.Id屬性進行任何交互,它都可以工作。 像這樣:

User _user = db.Users.Find(Id);
_user.Password = Password;
Console.Write(_user.Country.Id.ToString());
db.Entry(_user).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();

知道這是已知錯誤還是我做錯了什么?

謝謝!

使用實體框架時,我從未明確設置狀態。 如果刪除行db.Entry(_user).State = System.Data.Entity.EntityState.Modified; 您的代碼仍然可以正常工作並將數據保存到數據庫嗎?

您已經為實體配置了獨立的關聯( User上具有CountryId屬性)並且具有Required屬性,這意味着Country屬性需要具有一個值。

此代碼不會加載Country因為它是通過延遲加載而加載的。

User _user = db.Users.Find(Id);

除非你做類似的事情。

var country = _user.Country; // this will load the Country

或者,您可以使用緊急加載將Country與主要查詢一起加載。

User _user = db.Users.Include(x => x.Country).FirstOrDefault(x => x.Id == Id);

提示:

  • _user使用EntityState.Modified_user進行標記,因為它是代理,更改跟蹤器將知道是否將修改實體。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM