1
我一直在嘗試使用一對一的雙向關係映射兩個對象。兩個對象之間的關係不是必需的。下面是對象:流暢的NHibernate可以爲空的一對一映射
public class Tenant
{
public virtual int TenantId { get; set; }
public virtual string Name { get; set; }
public virtual Unit Unit { get; set; }
}
public class Unit
{
public virtual int UnitId { get; set; }
public virtual string UnitNumber { get; set; }
public virtual int Rooms { get; set; }
public virtual Tenant Tenant { get; set; }
}
,這裏是我想使用的映射:
public class Mappings : ClassMap<Unit>
{
/*
* Unit
* ------------
* UnitId (PK)
* TenantId (FK)
* Rooms
* UnitNumber
*/
public Mappings()
{
Id(x => x.UnitId).GeneratedBy.Identity();
References(x => x.Tenant);
Map(x => x.Rooms).Not.Nullable();
Map(x => x.UnitNumber).Not.Nullable();
}
}
public class TenantMapping : ClassMap<Tenant>
{
/*
* Tenant
* -------------
* TenantId (PK)
* Name
*/
public TenantMapping()
{
Id(x => x.TenantId).GeneratedBy.Identity();
Map(x => x.Name).Not.Nullable();
HasOne(x => x.Unit).PropertyRef(x => x.Tenant);
}
}
預期的表定義的映射註釋。我使用驗證映射測試失敗:
[Test]
public void SetTenantOnUnit()
{
int unitId = 0;
int tenantId = 0;
using (var session = factory.OpenSession())
{
var tenants = Builder<Tenant>.CreateListOfSize(5).Build();
var unit = Builder<Unit>.CreateNew().Build();
foreach(var tenant in tenants)
session.Save(tenant);
session.Save(unit);
unit.Tenant = tenants[3];
tenantId = unit.Tenant.TenantId;
session.SaveOrUpdate(unit);
unitId = unit.UnitId;
}
using (var session = factory.OpenSession())
{
var unit = session.Get<Unit>(unitId);
Assert.That(unit, Is.Not.Null);
Assert.That(unit.Tenant, Is.Not.Null);
Assert.That(unit.Tenant.TenantId, Is.EqualTo(tenantId), "Incorrect Tenant Id");
}
}
[Test]
public void SetUnitOnTenant()
{
int tenantId = 0;
int unitId = 0;
using (var session = factory.OpenSession())
{
var tenant = Builder<Tenant>.CreateNew().Build();
var units = Builder<Unit>.CreateListOfSize(5).Build();
session.Save(tenant);
foreach(var unit in units)
session.Save(unit);
tenant.Unit = units[3];
unitId = tenant.Unit.UnitId;
session.SaveOrUpdate(tenant);
tenantId = tenant.TenantId;
}
using (var session = factory.OpenSession())
{
var tenant = session.Get<Tenant>(tenantId);
Assert.That(tenant, Is.Not.Null);
Assert.That(tenant.Unit, Is.Not.Null);
Assert.That(tenant.Unit.UnitId, Is.EqualTo(unitId), "Incorrect unit id");
}
}
我已經包括源代碼在這裏:https://bitbucket.org/crmckenzie/fluentnhibernate.discovery/overview
理想情況下,我能夠創造從兩邊的關係,讓它成功保存到數據庫。我已經閱讀了StackOverFlow上的其他一對一映射主題,並且他們中的任何一個看起來都不直接點。我如何正確映射這種關係?