2

Im just trying to work out if its possible to map a 1 - 0..1 (one to at most one \ one to zero or one) relationship using fluent NHibernate without the use of a Private Collection. An example of the class structure is below:

    public class ClassA
    {
        public int ClassAId { get; set; }

        public string SomeDetails { get; set; }

        public ClassB ClassB { get; set; }

    }

    public class ClassB
    {
        public ClassA ClassA { get; set; }

        public int ClassBId { get; set; }

        public string SomeChildDetails { get; set; }
    }

In this example, ClassA can have a ClassB, or ClassB can be null.

The DB structure would look something like:

   ClassA Table
   -------------
   int ClassA_ID  PK
   string SomeDetails

   ClassB Table
   ------------
   int ClassA_Id   PK  FK
   string SomeChildDetails

In this situation, you cannot use HasOne(x => x.ClassB).Cascade.All(); as this assumes it must always have one.

Is there a way to do this without having a one to many relationship with a private IList on ClassA and having the getter of the ClassB property getting the first entry in the list.

Ta

R

4

1 回答 1

3

除了将映射上的所有属性标记为 之外virtualReferences还应该这样做:

References(x => x.ClassB).Nullable().Cascade.All();

Fluent NHibernate 的文档说它相当于多对一关系,但也适用于单个属性,最终是 1-0..1 关系。您可以尝试使用HasOnewithNullable()修饰符,但它在文档中说您通常应该使用它References

[编辑评论]:

据我所知,NHibernate 的默认外键命名策略是keyname_id,您可以通过实现自己的方式来更改它ForeignKeyConvention(这个适用于所有映射)。假设您的外键策略是 TableNameID,即“ClassBID”:

internal class MyFkeyConvention : ForeignKeyConvention
{
    protected override string GetKeyName(FluentNHibernate.Member property, Type type)
    {
        if(property != null)
            return property.Name + "ID";
        return type.Name + "ID";
    }
}

或者如果您只在一个地方需要它,就使用它:

References(x => x.ClassB).Column("YourForeignKeyColumnName").Nullable().Cascade.All();
于 2012-10-01T11:45:23.423 回答