我有Person和LoginAccount类,其中我想要一个到零或一个映射。即一个人可以拥有零个或只有一个登录帐户。
我试过这个.. Person.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<id name="PersonID">
<generator class="native" />
</id>
<property name="Title" />
<property name="FirstName" />
<property name="SecondName" />
<property name="ThirdName" />
<property name="LegalFullName" />
<property name="LegalFullNameLocal" />
<property name="AliasFullName" />
<property name="Suffix" />
<property name="PreviousLegalName" />
<property name="ReasonForNameChange" />
<many-to-one class="OESPCS.Model.LoginAccount" column="LoginAccountID" name="LoginAccount" foreign-key="fk_LoginAccountID_Person" unique="true">
</many-to-one>
LoginAccount.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<class name ="LoginAccount">
<id name="LoginAccountID">
<generator class="native" />
</id>
<property name="LoginId" unique="true" />
<property name="Password" />
<property name="SaltKey" />
<property name="PasswordChangedOnDate"/>
<property name="IsPasswordChangeRequired" />
<property name="IsKeepSignedIn" />
<property name="IsMultiSessionAllowed" />
<property name="PrivacyPolicyVersion" />
<property name="IsLocked" />
<property name="LockedOnDate" />
<property name="LockedTillDate" />
<property name="IsDisabled" />
<property name="DisabledOnDate" />
<property name="DisabledTillDate" />
<property name="LoginFailAttempts" />
<one-to-one class="OESPCS.Model.Person" name="person" foreign-key="fk_LoginAccount_PersonID"/>
</class>
在DB这个映射给了我一对一的映射但是在我的项目中人可能没有LoninAccount所以亲自表LoginAccountId可以为null但是因为我们在个人hbm中说unique = true所以它不允许多个次。
所以我需要进行一对一或一次映射吗?
如何解决这个问题?
答案 0 :(得分:0)
当您刚接触NHinernate时,您应该考虑使用Fluent NHibernate或NH-integrated自动化(3.2中引入)等代码映射技术。
以下示例代码(Fluent NHibernate)应该让您入门:
public class LoginAccount
{
public virtual Int Id { get; set; };
public virtual string Password { get; set; };
public virtual string Saltkey { get; set; };
public virtual Person BelongsTo{ get; set; }
public LoginAccount()
{
}
}
public class LoginAccountMap: ClassMap<LoginAccount>
{
public LoginAccountMap()
{
Id(x => x.Id);
Map(x => x.Password);
Map(x => x.Saltkey);
References(c => c.BelongsTo).Cascade.None().Fetch.Join().NotFound.Ignore();
}
}
public class Person
{
public virtual Int Id { get; set; };
public virtual string FirstName { get; set; };
public virtual string SureName { get; set; };
public virtual LoginAccount UserAcc{ get; set; }
public Person()
{
}
}
public class PersonMap: ClassMap<Person>
{
public PersonMap()
{
Id(x => x.Id);
Map(x => x.FirstName);
Map(x => x.SureName);
References(c => c.UserAcc).Cascade.SaveUpdate().Fetch.Join().NotFound.Ignore();
}
}