我试图插入数据库。我有以下两个实体:
用户:
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();
}
}
}
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();
}
}
}
我通过的JSON看起来如下:
{
"Email": "Example3@gmail.com",
"Username": "Something123",
"UserDescription": {
"Firstname": "John",
"Lastname": "Doe"
}
}
我尝试对用户进行插入,希望它能够级联并插入到子表UserDescription中,但这并不起作用。所以我先插入用户,然后插入UserDescription(不确定这是否理想)。
无论如何,当我成功插入用户后尝试插入UserDescription时出现以下错误:
not-null属性引用null或transient值Users.Entities.UserDescription.User
有什么建议吗?
答案 0 :(得分:0)
如果有人感兴趣,我删除了&#34; .Constrained()&#34;在UserDescription映射中,这似乎工作。虽然我不知道这是否是最佳解决方案!