簡體   English   中英

EF DbSet.Find()返回分離的實體

[英]EF DbSet.Find() returns Detached Entity

我有一個非常簡單的Entity ,只有四個字段:名稱,州,城市和ID以及一些驗證。

[Table("Places")]
public class Place : BindableBase, IDataErrorInfo
{
    private string name;
    private string city;
    private Estado state;
    private int id;

    [Required]
    [StringLength(500)]        
    public string Name
    {
        get { return this.name; }
        set { SetProperty(ref name, value); }
    }

    [Required]
    [StringLength(500)]
    public string City
    {
        get { return this.city; }
        set { SetProperty(ref city, value); }
    }

    [Required]        
    public State State
    {
        get { return this.state; }
        set { SetProperty(ref state, value); }
    }

    [Key]
    public int Id
    {
        get { return this.id; }
        set { SetProperty(ref id, value); }
    }

    [NotMapped]
    public bool IsValid
    {
        get 
        {
            return Validator.TryValidateObject(this, new ValidationContext(this), new Collection<ValidationResult>(), true);
        }
    }

    #region IDataErrorInfo Members
    /// <summary>
    /// IDataErrorInfo Interface Error Message for the object.
    /// </summary>
    [NotMapped]
    public string Error
    {
        get { throw new NotImplementedException(); }
    }

    public string this[string propertyName]
    {
        get 
        {
            var context = new ValidationContext(this)
            {
                MemberName = propertyName
            };

            var results = new Collection<ValidationResult>();
            bool isValid = Validator.TryValidateObject(this, context, results, true);

            if (!isValid)
            {
                ValidationResult result = results.SingleOrDefault(p =>
                                                                  p.MemberNames.Any(memberName =>
                                                                                    memberName == propertyName));

                return result == null ? null : result.ErrorMessage;
            }

            return null; 
        }
    }
    #endregion
}

我可以將它添加到數據庫中,但是一旦嘗試對其進行更新,就會出現異常。

我在用:

public void UpdatePlace(Place place)
{
    var entity = context.Places.Find(place.Id);

    if (entity == null)
    {
        throw new InvalidOperationException("Place not found.");
    }

    context.Entry(place).CurrentValues.SetValues(place);
    context.SaveChanges();
}

當我到達

context.Entry(place).CurrentValues.SetValues(place);

我得到一個異常為:

System.InvalidOperationException

“不能為類型'Place'的實體調用成員'CurrentValues',因為該實體在上下文中不存在。要將實體添加到上下文中,請調用DbSet的Add或Attach方法。”

context.Entry向我展示了該實體確實是分離的

context.Entry顯示分離

但是DbSet.Find()方法的文檔清楚地表明,如果在數據庫中找到了一個,則Find()應該返回一個附加的實體:

查找具有給定主鍵值的實體。 如果上下文中存在具有給定主鍵值的實體,則將立即返回該實體,而無需向商店提出請求。 否則,將向商店請求具有給定主鍵值的實體,如果找到實體,則將該實體附加到上下文並返回 如果在上下文或存儲中未找到任何實體,則返回null。

因此,當我嘗試獲取CurrentValues ,由於該實體是分離的,因此它將引發Exception ...但據我所知,應該有一個附加的實體,或者為null,沒有其他任何東西。

我無法在線找到有關此錯誤的任何信息,我使用SQL CE 4.0作為數據庫,有人知道發生了什么嗎?

我想我每次可以從Find獲取實體時都可以Attach該實體,但我仍然想了解我的軟件正在發生什么,因為這不應該發生。

我認為您應該將這一行更改為:

  context.Entry(entity).CurrentValues.SetValues(place);

暫無
暫無

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

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