[英]Fluent nHibernate Mapping - 1 to 0..1
I have 2 tables: 我有2张桌子:
TableA (Id, Name, UpdateDate)
TableB (Id, TableAId, Amount)
My domain objects look like this: 我的域对象如下所示:
TableA
public virtual Guid Id {get;set;}
public virtual String Name {get;set;}
public virtual TableB TableB {get; set;}
TableB
public virtual Guid Id {get;set;}
public virtual decimal Amount {get;set;}
public virtual TableA TableA {get;set;}
How would I map these tables so whenever I query for TableA
, I get its reference in TableB
if there is one? 我将如何映射这些表,以便每当查询
TableA
(如果有的话)在TableB
获得它的引用?
In my TableA mapping: 在我的TableA映射中:
Component(x => x.TableB,
m => m.References(x => x.TableA).Column("TableAId").Nullable());
I think this is more appropiate 我觉得这比较合适
public virtual IList<TableB> TableB { get; set; }
Because you can have many items in TableB referencing the same item in TableA. 因为在TableB中可以有很多项目引用TableA中的同一项目。 For the Mapping this should work:
对于映射,这应该起作用:
public TableAMapping : ClassMap<TableA>
{
public TableAMapping()
{
// other struff
HasMany(x => x.TableB).Table("TableB").KeyColumn("TableAId");
}
}
For TableB 对于TableB
public TableBMapping : ClassMap<TableB>
{
public TableBMapping()
{
// other struff
Reference(x => x.TableA)Column("TableAId");
}
}
UPDATE 更新
For 1 to 1 一对一
HasOne(x => x.TableB).ForeignKey("TableAId");
If you are using Fluen Mapping you can try like this: 如果您正在使用Fluen映射,则可以这样尝试:
public TableAMap()
{
Table("TableA");
Id(x=> x.Id).GeneratedBy.Assigned();
Map(x=> x.Name).Not.Nullable();
References(x => x.TableB, TableBId);
}
public TableBMap()
{
Table("TableB");
Id(x=> x.Id).GeneratedBy.Assigned();
Map(x=> x.Amount).Not.Nullable();
HasMany<TableA>(x => x.TableA)
.Nullable()
.KeyColumn("TableAId");
}
If you want to ensure that it is an 1 to 1 you may use "HasOne" instead References. 如果要确保其为1到1,则可以使用“ HasOne”代替“引用”。
I figured out the answer. 我想出了答案。 Using the exact schema I listed in my question, I was able to map TableA to TableB like this.
使用我在问题中列出的确切模式,我能够像这样将TableA映射到TableB。
HasOne(x => x.TableB).PropertyRef(m => m.TableA).Cascade.All();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.