[英]Fluent nHibernate “not-null property references a null or transient value” with Foreign Key
I'm trying to do an insert into a database. 我正在尝试插入数据库。 I have the following two entities:
我有以下两个实体:
USER: 用户:
public class User
{
private UserDescription _userDescription;
public virtual uint Id { get; set; }
public virtual string Email { get; set; }
public virtual string Username { get; set; }
public virtual UserDescription UserDescription
{
get { return _userDescription; }
set { _userDescription = value; }
}
public virtual void Add(UserDescription userDescription)
{
if (_userDescription != null)
{
_userDescription.User = null;
}
_userDescription = userDescription;
_userDescription.User = this;
}
public class UserMap : ClassMap<User>
{
public UserMap()
{
Table("users");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Email).Not.Nullable();
Map(x => x.Username).Not.Nullable();
HasOne(x => x.UserDescription).Cascade.All().LazyLoad();
}
}
}
And USERDESCRIPTION : 和USERDESCRIPTION :
public class UserDescription
{
public virtual uint Id { get; set; }
public virtual User User { get; set; }
public virtual uint UserId { get; set; }
public virtual string Firstname { get; set; }
public virtual string Lastname { get; set; }
public class UserDescrptionMap : ClassMap<UserDescription>
{
public UserDescrptionMap()
{
Table("usersdescription");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.UserId);
Map(x => x.Firstname);
Map(x => x.Lastname);
HasOne(x => x.User).Constrained().ForeignKey();
}
}
}
And my JSON that I pass through looks like the following: 我通过的JSON如下所示:
{
"Email": "Example3@gmail.com",
"Username": "Something123",
"UserDescription": {
"Firstname": "John",
"Lastname": "Doe"
}
}
I tried doing an insert into User hoping that it would cascade down and also insert into the child table UserDescription, but that didn't work. 我尝试对User进行插入,希望它可以向下层叠并插入子表UserDescription中,但这没用。 So instead I insert into user first then insert into UserDescription (not sure if this is ideal).
因此,我先插入用户,然后再插入UserDescription(不确定这是否理想)。
Anyway, I get the following error when I try to insert into UserDescription after I successfully insert to User: 无论如何,当我成功插入到User后尝试插入UserDescription时,出现以下错误:
not-null property references a null or transient value Users.Entities.UserDescription.User
not-null属性引用null或瞬态值Users.Entities.UserDescription.User
Any suggestions? 有什么建议么?
In case anyone's interested, I removed the ".Constrained()" in the UserDescription Mapping and that seemed to work. 如果有人感兴趣,我在UserDescription映射中删除了“ .Constrained()”,这似乎可行。 Although I dont know if that is the best solution!
虽然我不知道这是否是最好的解决方案!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.