我正试图插入数据库。我有以下两个实体:
用户:

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();
        }
    }
}

和用户描述:
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": "[email protected]",
   "Username": "Something123",
   "UserDescription": {
       "Firstname": "John",
       "Lastname": "Doe"
   }
}

我试着在UserDescription子表中插入一个insert,希望它能向下层叠并插入,但是没有成功。因此,我先插入到user,然后插入到UserDescription(不确定这是否是理想的)。
无论如何,在成功插入到用户后,尝试插入到用户描述中时,会出现以下错误:
not null属性引用空值或临时值Users.Entities.UserDescription.User
有什么建议吗?

最佳答案

如果有人感兴趣,我删除了UserDescription映射中的“.Constrained()”,这似乎很有用。尽管我不知道这是否是最好的解决办法!

07-24 09:32