Nikhil Vasdev
Nikhil Vasdev

Reputation: 193

Map Two Tables With Third Table Fluent Nhibernate

I am working on Nhibernate and I have two classes name Customer and CusotmerRole with their mapping(CustomerMap and CustomerRoleMap). Now I want to map these two tables with the Third Table we have in Database named As Customer_CustomerRole_Mapping. The Table Customer_CustomerRole_Mapping have two Columns in the database one Is Customer_Id(Primary key as well as ForeignKey with Customer Table and another is CustomerRole_Id which is also PrimaryKey and Foreign Key with CustomerRole table. So I want to know that How can I map Customer_CustomerRole_Mapping with Customer and CustomerRole. Also I need to ask that I have to create another map for this or I can map these existing classes. Thanks in Advance.

Code:

Customer.Cs :

public class Customer : BaseEntity
{
    private ICollection<ExternalAuthenticationRecord> _externalAuthenticationRecords;
    private ICollection<CustomerRole> _customerRoles;
    private ICollection<ShoppingCartItem> _shoppingCartItems;
    private ICollection<RewardPointsHistory> _rewardPointsHistory;
    private ICollection<ReturnRequest> _returnRequests;
    private ICollection<Address> _addresses;

    /// <summary>
    /// Ctor
    /// </summary>
    public Customer()
    {
        this.CustomerGuid = Guid.NewGuid();
        this.PasswordFormat = PasswordFormat.Clear;
    }

    /// <summary>
    /// Gets or sets the customer Guid
    /// </summary>
    public virtual Guid CustomerGuid { get; set; }

    /// <summary>
    /// Gets or sets the username
    /// </summary>
    public virtual string Username { get; set; }
    /// <summary>
    /// Gets or sets the email
    /// </summary>
    public virtual string Email { get; set; }
    /// <summary>
    /// Gets or sets the password
    /// </summary>
    public virtual string Password { get; set; }

    /// <summary>
    /// Gets or sets the password format
    /// </summary>
    public virtual int PasswordFormatId { get; set; }
    /// <summary>
    /// Gets or sets the password format
    /// </summary>
    public virtual PasswordFormat PasswordFormat
    {
        get { return (PasswordFormat)PasswordFormatId; }
        set { this.PasswordFormatId = (int)value; }
    }
    /// <summary>
    /// Gets or sets the password salt
    /// </summary>
    public virtual string PasswordSalt { get; set; }

    /// <summary>
    /// Gets or sets the admin comment
    /// </summary>
    public virtual string AdminComment { get; set; }

    /// <summary>
    /// Gets or sets a value indicating whether the customer is tax exempt
    /// </summary>
    public virtual bool IsTaxExempt { get; set; }

    /// <summary>
    /// Gets or sets the affiliate identifier
    /// </summary>
    public virtual int AffiliateId { get; set; }

    /// <summary>
    /// Gets or sets the vendor identifier with which this customer is associated (maganer)
    /// </summary>
    public virtual int VendorId { get; set; }

    /// <summary>
    /// Gets or sets a value indicating whether the customer is active
    /// </summary>
    public virtual bool Active { get; set; }

    /// <summary>
    /// Gets or sets a value indicating whether the customer has been deleted
    /// </summary>
    public virtual bool Deleted { get; set; }

    /// <summary>
    /// Gets or sets a value indicating whether the customer account is system
    /// </summary>
    public virtual bool IsSystemAccount { get; set; }

    /// <summary>
    /// Gets or sets the customer system name
    /// </summary>
    public virtual string SystemName { get; set; }

    /// <summary>
    /// Gets or sets the last IP address
    /// </summary>
    public virtual string LastIpAddress { get; set; }

    /// <summary>
    /// Gets or sets the date and time of entity creation
    /// </summary>
    public virtual DateTime CreatedOnUtc { get; set; }

    /// <summary>
    /// Gets or sets the date and time of last login
    /// </summary>
    public virtual DateTime? LastLoginDateUtc { get; set; }

    /// <summary>
    /// Gets or sets the date and time of last activity
    /// </summary>
    public virtual DateTime LastActivityDateUtc { get; set; }

    #region Navigation properties

    /// <summary>
    /// Gets or sets customer generated content
    /// </summary>
    public virtual ICollection<ExternalAuthenticationRecord> ExternalAuthenticationRecords
    {
        get { return _externalAuthenticationRecords ?? (_externalAuthenticationRecords = new List<ExternalAuthenticationRecord>()); }
        protected set { _externalAuthenticationRecords = value; }
    }

    /// <summary>
    /// Gets or sets the customer roles
    /// </summary>
    public virtual ICollection<CustomerRole> CustomerRoles
    {
        get { return _customerRoles ?? (_customerRoles = new List<CustomerRole>()); }
        protected set { _customerRoles = value; }
    }

    /// <summary>
    /// Gets or sets shopping cart items
    /// </summary>
    public virtual ICollection<ShoppingCartItem> ShoppingCartItems
    {
        get { return _shoppingCartItems ?? (_shoppingCartItems = new List<ShoppingCartItem>()); }
        protected set { _shoppingCartItems = value; }
    }

    /// <summary>
    /// Gets or sets reward points history
    /// </summary>
    public virtual ICollection<RewardPointsHistory> RewardPointsHistory
    {
        get { return _rewardPointsHistory ?? (_rewardPointsHistory = new List<RewardPointsHistory>()); }
        protected set { _rewardPointsHistory = value; }
    }

    /// <summary>
    /// Gets or sets return request of this customer
    /// </summary>
    public virtual ICollection<ReturnRequest> ReturnRequests
    {
        get { return _returnRequests ?? (_returnRequests = new List<ReturnRequest>()); }
        protected set { _returnRequests = value; }
    }

    /// <summary>
    /// Default billing address
    /// </summary>
    public virtual Address BillingAddress { get; set; }

    /// <summary>
    /// Default shipping address
    /// </summary>
    public virtual Address ShippingAddress { get; set; }

    /// <summary>
    /// Gets or sets customer addresses
    /// </summary>
    public virtual ICollection<Address> Addresses
    {
        get { return _addresses ?? (_addresses = new List<Address>()); }
        protected set { _addresses = value; }
    }

    #endregion
}

CustomerRole.cs:

 public  partial class CustomerRole : BaseEntity
    {
        private ICollection<PermissionRecord> _permissionRecords;
        /// <summary>
        /// Gets or sets the customer role name
        /// </summary>
        public virtual string Name { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether the customer role is marked as free shiping
        /// </summary>
        public virtual bool FreeShipping { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether the customer role is marked as tax exempt
        /// </summary>
        public virtual bool TaxExempt { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether the customer role is active
        /// </summary>
        public virtual bool Active { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether the customer role is system
        /// </summary>
        public virtual bool IsSystemRole { get; set; }

        /// <summary>
        /// Gets or sets the customer role system name
        /// </summary>
        public virtual string SystemName { get; set; }

        /// <summary>
        /// Gets or sets a product identifier that is required by this customer role. 
        /// A customer is added to this customer role once a specified product is purchased.
        /// </summary>
        public virtual int PurchasedWithProductId { get; set; }

        /// <summary>
        /// Gets or sets the permission records
        /// </summary>
        public virtual  ICollection<PermissionRecord> PermissionRecords
        {
            get { return _permissionRecords ?? (_permissionRecords = new List<PermissionRecord>()); }
            protected set { _permissionRecords = value; }
        }
    }

CustomerMap.cs:

 public class CustomerMap : ClassMap<Customer>
    {
        public CustomerMap()
        {
            Table("Customer");
            LazyLoad();
            Id(x => x.Id).GeneratedBy.Identity().Column("Id");                
            Map(x => x.CustomerGuid).Column("CustomerGuid").Not.Nullable();
            Map(x => x.Username).Column("Username").Length(1000);
            Map(x => x.Email).Column("Email").Length(1000);
            Map(x => x.Password).Column("Password");
            Map(x => x.PasswordFormatId).Column("PasswordFormatId").Not.Nullable().Precision(10);
            Map(x => x.PasswordSalt).Column("PasswordSalt");
            Map(x => x.AdminComment).Column("AdminComment");
            Map(x => x.IsTaxExempt).Column("IsTaxExempt").Not.Nullable();
            Map(x => x.AffiliateId).Column("AffiliateId").Not.Nullable();
            Map(x => x.VendorId).Column("VendorId").Not.Nullable();
            Map(x => x.Active).Column("Active").Not.Nullable();
            Map(x => x.Deleted).Column("Deleted").Not.Nullable();
            Map(x => x.IsSystemAccount).Column("IsSystemAccount").Not.Nullable();
            Map(x => x.SystemName);
            Map(x => x.LastIpAddress);
            Map(x => x.CreatedOnUtc).Column("CreatedOnUtc").Not.Nullable();
            Map(x => x.LastLoginDateUtc).Column("LastLoginDateUtc");
            Map(x => x.LastActivityDateUtc).Column("LastActivityDateUtc");
            References(x => x.BillingAddress).Column("BillingAddress_Id");
            References(x => x.ShippingAddress).Column("ShippingAddress_Id");

        }


    }

CustomerRoleMap.cs:

public class CustomerRoleMap : ClassMap<CustomerRole>
    {
        public CustomerRoleMap()
        {
            Table("CustomerRole");
            LazyLoad();
            Id(x => x.Id).GeneratedBy.Identity().Column("Id");
            Map(x => x.Name).Column("Name").Not.Nullable().Length(255);
            Map(x => x.FreeShipping).Column("FreeShipping").Not.Nullable();
            Map(x => x.TaxExempt).Column("TaxExempt").Not.Nullable();
            Map(x => x.Active).Column("Active").Not.Nullable();
            Map(x => x.IsSystemRole).Column("IsSystemRole").Not.Nullable();
            Map(x => x.SystemName).Column("SystemName").Length(255);
            Map(x => x.PurchasedWithProductId).Column("PurchasedWithProductId").Not.Nullable().Precision(10);

            HasMany<CustomerRole>(x => x.Id).Table("Customer_CustomerRole_Mapping").KeyColumn("CustomerRole_Id");
        }
    }

Upvotes: 0

Views: 160

Answers (1)

granadaCoder
granadaCoder

Reputation: 27884

If you only have the two FK's in the table " Customer_CustomerRole_Mapping." , you do ~not need a separate mapping for this table.

If your " Customer_CustomerRole_Mapping." has its own SurrogateKey, or any other columns besides the two FK's...you will need a mapping (and a poco/pojo class for this mapping).

Customer Mapping

        /* the below is how to do it without a surogatekey on the link table */
        HasManyToMany<CustRoleNHEntity>(x => x.CustRoles)
       .Table("Customer_CustomerRole_Mapping")
            .ParentKeyColumns.Add("AbcCustomerUUID", p => p.UniqueKey("Emp_CustRole_Unique").Index("IX_ABC123"))
            .ChildKeyColumns.Add("AbcCustRoleUUID", p => p.UniqueKey("Emp_CustRole_Unique"))
            .Cascade.None()
            ;

CustRole Mapping

        /* the below is how to do it without a surogatekey on the link table */
        HasManyToMany<CustomerNHEntity>(x => x.MyCustomers) /* I think this is missing on the POCO */
       .Table("Customer_CustomerRole_Mapping")
            .ParentKeyColumns.Add("AbcCustRoleUUID", p => p.UniqueKey("Emp_CustRole_Unique").Index("IX_ABC123"))
            .ChildKeyColumns.Add("AbcCustomerUUID", p => p.UniqueKey("Emp_CustRole_Unique"))
            .Cascade.None()
            ;

You need an ICollection of Customers on the CustomerRole poco/pojo, which I call "MyCustomers" in the CustRole mapping.

Upvotes: 0

Related Questions