【问题标题】:Entity Framework Is not saving child object of context实体框架不保存上下文的子对象
【发布时间】:2014-06-26 17:38:07
【问题描述】:

我正在尝试使用实体框架,但我的设计遇到了问题。我的 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()
        {

        }

    }

【问题讨论】:

标签: c# .net entity-framework


【解决方案1】:

嗯,你在很多方面都出错了。

首先,虽然技术上没有错误,但命名很奇怪。您最好使用一致的命名约定。如果您确实需要其中的 JK,只需将其称为 UserProfile 或 UserProfileJK 或其他名称。

其次,您将 jk_userProfile 创建为字段,而不是属性。实体框架不适用于字段。它仅适用于属性,因此您需要将其设为一个。

第三,不要向你的 DbContext 添加方法,创建一个不同的数据层类来执行你的业务逻辑,并让它使用你的 DbContext。

【讨论】:

  • 感谢您的回复!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多