3

我在 NHibernate 中使用新的 Map by Code 片段。我的理解是在 NHibernate 3 中进行了更新,以便单向一对多关系不再在外键上插入 null 然后将其更新为正确的值,只要您在集合上设置 inverse=false 并进行外键不可为空。

我看到的是 NHibernate 现在插入了正确的外键,但它仍然发出一个额外的 UPDATE 将外键设置为插入中使用的值?!?

我在映射中做错了什么吗?(一个用户可以有多个密码。密码对象不会引用我域中的用户。)

mapper.Class<Password>(map =>
{
    map.Table("Passwords");
    map.Id(x => x.Id, x => { x.Generator(Generators.Native); x.Column("PasswordId"); });
    map.Property(x => x.PasswordFormat, x => { x.NotNullable(true); });
    map.Property(x => x.Salt, x => { x.Length(100); });
    map.Property(x => x.PasswordValue, x => { x.NotNullable(true); x.Length(500); });
    map.Property(x => x.CreateDate, x => { x.NotNullable(true); });
});

mapper.Class<User>(map =>
{
    map.Table("Users");
    map.Id(x => x.Id, x => { x.Generator(Generators.Native); x.Column("UserId"); });
    map.Property(x => x.UserName, x => { x.NotNullable(true); x.Length(100); x.UniqueKey("UX_Users_Username"); });
    map.Property(x => x.Email, x => { x.Length(100); x.Index("IX_Users_Email"); });
    map.Property(x => x.IsAnonymous, x => { x.NotNullable(true); });
    map.Property(x => x.IsApproved, x => { x.NotNullable(true); });
    map.Property(x => x.LastActivityDate, x => { x.NotNullable(true); });
    map.Property(x => x.CreateDate, x => { x.NotNullable(true); });
    map.Set(x => x.Passwords, x => { x.Access(Accessor.Field); x.Inverse(false); x.Key(k => { k.Column("UserId"); k.NotNullable(true); k.ForeignKey("FK_Passwords_UserId"); }); x.Cascade(Cascade.All); x.Lazy(CollectionLazy.Lazy); }, x => x.OneToMany());
});

注意:这是使用内置的 NHibernate.Mapping.ByCode,而不是 Fluent NHibernate。

4

2 回答 2

2

事实证明,我可以通过设置k.Update(false)Passwords 集合映射的外键部分来完成此操作。

hazzik 对以下问题的回答让我排队。

https://stackoverflow.com/a/11576097/139694

于 2012-12-17T23:23:06.937 回答
1

它应该是 Inverse() 而不是 Inverse(false)。

Inverse() 表示其他实体拥有该关系,它负责在插入/更新信息时为 NHibernate 提供有关该关系的数据,即,如果“用户”设置为反向,则“密码”需要负责提供关系信息. 到 NHibernate。

为此,您需要在“密码”实体上设置“用户”参考属性。在创建/更新密码时,明确分配用户属性。

//create new password
Password objPassword = new Password();
objPassword.otherproperties =///assign
objPassword.User = <<---assign the user property

目前,您有 Inverse(false) 这是 NHibernate 的默认设置。在这种情况下,insert 语句将在 passwordid 为 null 的情况下执行,然后更新引用,从而导致两个操作。

于 2012-12-17T22:22:55.390 回答