我一直在尝试使用一对一的双向关系映射两个对象。两个对象之间的关系不是必需的。以下是对象:
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 上的其他一对一映射主题,但似乎没有一个是直接的。如何正确映射这种关系?