簡體   English   中英

實體框架未保存上下文的子對象

[英]Entity Framework Is not saving child object of context

我正在嘗試使用實體框架,但是我的設計遇到了問題。 我的UserProfile類具有三個字段,UserId,UserName和jk_userHandle,前兩個更新並且在我對對象進行更改時可以保存。 但是,我什至不能創建非空版本的jk_userHandle。 我不確定我哪里出錯了。

我有google / stackoverflow這個到地獄,問我辦公室里的人,似乎沒人知道-_-

public class UsersContext : DbContext
    {
        public UsersContext()
            : base("DefaultConnection")
        {
        }
public DbSet<UserProfile> UserProfiles { get; set; }

public void changeDataItem_edit(UserProfile choice, jk_userProfile model)
        {
            var found = UserProfiles.Find(choice.UserId); //finds prof
            if (found == null) throw new KeyNotFoundException();

            UserProfile tempProfile = choice;
            tempProfile.jk_userHandle = model;
/*
stuff i found on stackoverflow, but 
found.jk_userHandle = model;
or
found.jk_userHandle.biography = model.biography
don't work either. In all scenarios, when I step through i see my dbset's value change, but will not persist out of the http post. I've tried db.SaveChanges() (outside this function call) as well.

Stackoverflow link: http://stackoverflow.com/questions/7850774/updating-a-reference-to-a-child-object-in-entity-framework-4-1-codefirst
*/

            this.Entry(found).CurrentValues.SetValues(tempProfile);
            found.jk_userHandle = tempProfile.jk_userHandle;

            this.SaveChanges();
        }
}

這是userprofile類:

[Table("UserProfile")]
    public class UserProfile
    {
        public jk_userProfile jk_userHandle; //is the handle for the rest of the account info...
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        public string UserName { get; set; }
        public UserProfile()
        {
            jk_userHandle = new jk_userProfile();
        }
    }

以防萬一,這是jk_userHandle

 public class jk_userProfile
    {

        public string userName { get; set; }

        [DataType(DataType.Date)]
        public string lastLogin { get; set; }


        [DataType(DataType.Date)]
        public string creationDate { get; set; }


        [DataType(DataType.MultilineText)]
        [Display(Name = "Just Connekt Biography", Description = "Write about yourself, favorite movies, shows, activities, what you like to do, etc...")]
        public string biography { get; set; }

        public jk_userProfile()
        {

        }

    }

好吧,您在許多方面都出了問題。

首先,雖然在技術上沒有錯,但命名卻很奇怪。 您最好使用一致的命名約定。 只需將其命名為UserProfile或UserProfileJK即可,如果您確實需要JK,則可以使用它。

其次,已將jk_userProfile創建為字段而不是屬性。 實體框架不適用於字段。 它僅適用於屬性,因此您需要使其成為一體。

第三,不要像這樣向DbContext添加方法,不要創建其他數據層類來執行業務邏輯,而要使用DbContext。

暫無
暫無

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

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