简体   繁体   中英

NHibernate fluent mapping to an entity property

I have a table called "Customers" and in this table there are store and office address. In the code there is a Customer class with two properties that are of type Address (one for StoreAddress and OfficeAddress ).

public class Customer
{
    public virtual int Id { get; set;}
    public virtual string Name {get;set;}
    public virtual string Email {get; set;}
    public virtual Address StoreAddress {get; set;}
    public virtual Address OfficeAddress {get; set;}
}

public class Address
{
    public string Address1 {get; set;}
    public string Address2 {get; set;}
    public string State {get; set;}
    public string City {get; set;}
    public string Zip  {get; set;}
}

I can map items that are not of an entity type Address but not sure how to map to another entity property within the customer entity?..

Table("Customers");
Schema("dbo);
Id(x => x.ID).Column("CustomerId");
Map(x => x.Name);
Map(x => x.Email);

How would I be able to map to my StoreAddress and OfficeAddress from the table Customers table?

In case, I understand your missing point, we can use:

References / many-to-one

References is for creating many-to-one relationships between two entities, and is applied on the "many side." You're referencing a single other entity, so you use the References method. #HasMany / one-to-many is the "other side" of the References relationship, and gets applied on the "one side."

Table("Customers");
Schema("dbo);
Id(x => x.ID).Column("CustomerId");
Map(x => x.Name);
Map(x => x.Email);
// this is the fluent way for many-to-one
References(x => x.StoreAddress);
References(x => x.OfficeAddress); 

The complete overview of the References() syntax could be found here: Mapping-by-Code - ManyToOne (by Adam Bar) - which is about mapping-by-code, but provides comparison with fluent syntax (the second half of the post)

You can use component mapping :

Component(x => StoreAddress).ColumnPrefix("StoreAddress");
Component(x => OfficeAddress).ColumnPrefix("OfficeAddress");

Then create a component map for Address type:

public class AddressMap : ComponentMap<Address>
{
    public AddressMap()
    {
        //map properterties
    }
}

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