简体   繁体   中英

Fluent nHibernate Mapping - 1 to 0..1

I have 2 tables:

   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?

In my TableA mapping:

   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. For the Mapping this should work:

public TableAMapping : ClassMap<TableA>
{
    public TableAMapping()
    {
        // other struff
        HasMany(x => x.TableB).Table("TableB").KeyColumn("TableAId");
    }
}

For 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:

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.

I figured out the answer. Using the exact schema I listed in my question, I was able to map TableA to TableB like this.

HasOne(x => x.TableB).PropertyRef(m => m.TableA).Cascade.All();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM