我正在尝试设置从我的用户到 UserDetails 表的一对一映射。假设我的数据库中有以下表格:
Users:
- UserID (PK, Identity)
- UserName
- Password
UsersDetails:
- UserID (PK, FK)
- FirstName
- LastName
我创建了以下 poco 类:
public class User {
public virtual int UserID { get; set; }
public virtual string UserName { get; set; }
public virtual string Password { get; set; }
public virtual UserDetails Details { get; set; }
}
public class UserDetails {
public virtual int UserID { get; set; }
public virtual User User { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public UserDetails() {
}
public UserDetails(User user) {
User = user;
}
}
哪些被流畅地映射(请注意 xml 映射非常相似,如果您只知道 xml 映射,那么我仍然会感谢您的指导):
public class UserMap : ClassMap<User> {
public UserMap() {
Table("Users");
Id(x => x.UserID);
Map(x => x.UserName);
Map(x => x.Password);
HasOne(x => x.Details)
.Constrained()
.Cascade.All();
}
}
public class UserDetailsMap : ClassMap<UserDetails> {
public UserDetailsMap() {
Table("UsersDetails");
Id(x => x.UserID)
.GeneratedBy.Foreign("User");
HasOne(x => x.User)
.Constrained();
Map(x => x.FirstName);
Map(x => x.LastName);
}
}
一切都正确显示,但如果我说:
var user = new User() { UserName = "Test", Password = "Test" };
user.Details = new UserDetails(user) { FirstName = "Test", LastName = "Test" };
session.Save(user);
我得到错误:
“NHibernate.Id.IdentifierGenerationException:为:UserDetails 生成了空 id。”
如果有人能告诉我我做错了什么,我将不胜感激。谢谢
编辑:感谢 Jamie Ide 的建议。我已将我的用户映射更改为:
public class UserMap : ClassMap<User> {
public UserMap() {
Table("Users");
Id(x => x.UserID);
Map(x => x.UserName);
Map(x => x.Password);
References(x => x.Details, "UserID")
.Class<UserDetails>()
.Unique();
}
}
但是现在当我插入一个用户时,我得到了错误:
“System.ArgumentOutOfRangeException:索引超出范围。必须为非负数且小于集合的大小。”
如果我将 Cascade.All() 添加到我的参考中,我会收到关于生成的空 id 的原始错误。