[英]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.