MarimerLLC / cslaforum

Discussion forum for CSLA .NET
https://cslanet.com
Other
31 stars 6 forks source link

Child collection lazy loading on TabItem control. CSLA + MVVM light + WPF #85

Open jchabot1979 opened 8 years ago

jchabot1979 commented 8 years ago

Hi. I would like to know what is the best way to lazy load a child collection that a tab item is binded to on a tab control. I'm using CSLA, WPF, MVVM Light. I have a main view "Customer" that is an Add/Edit view. The viewModel is CustomerViewModel and has an instance of a BusinessBase "Customer" object. THis customer object has a child collection "Contacts", This contact collection is a BusinessListBase object and the BusinessBase object that is implemented in the collection is "Contact". I have a tab control with on the second tab item a user control that use the CustomerViewModel like all my 6 tab item's User control. I have a datagrid on the Contacts userControl that is binded on the Contacts child collection of the Customer object. I don't want to Fetch the Contacts from the database while loading the Customer object. I want to dynamically load it on demand the first time the user will click on the tabItem. I tough Lazy loading would be the solution. I tried setting the contactCollection as RelationshipTypes Child and LazyLoad and Fetching the data in the getter, but the getter is called at the load of the CustomerView and not when I click on the Contacts tab item. Can someone help me with it? Is there something I'm not doing good? Don't look at the adresss and Notes child collection, they are not implemented well.

Here's my BusinessObject Customer. I know there's a lot of code, but if it can help to understand. Thanks a lot

using Csla; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks;

namespace PortesDecko.BusinessObjects.MF_Customer { [Serializable] public class Customer : Base.CORE.BusinessObjects.CustomBusinessBase { private Customer() : base() { /* Require use of factory methods */ }

    #region Properties

    #region Root Properties

    public static readonly PropertyInfo<long> IDProperty = RegisterProperty<long>(c => c.ID);
    public long ID
    {
        get { return GetProperty(IDProperty); }
        private set { LoadProperty(IDProperty, value); }
    }

    public static readonly PropertyInfo<string> CodeProperty = RegisterProperty<string>(c => c.Code);
    public string Code
    {
        get { return GetProperty(CodeProperty); }
        private set { LoadProperty(CodeProperty, value); }
    }

    public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(c => c.Name);
    public string Name
    {
        get { return GetProperty(NameProperty); }
        set { SetProperty(NameProperty, value); }
    }

    public static readonly PropertyInfo<bool> IsActiveProperty = RegisterProperty<bool>(c => c.IsActive);
    public bool IsActive
    {
        get { return GetProperty(IsActiveProperty); }
        set { SetProperty(IsActiveProperty, value); }
    }

    public static readonly PropertyInfo<MF_Customer.Customer._Address> HeadOfficeAddressProperty = RegisterProperty<MF_Customer.Customer._Address>(c => c.HeadOfficeAddress);
    public MF_Customer.Customer._Address HeadOfficeAddress
    {
        get { return GetProperty(HeadOfficeAddressProperty); }
        private set { LoadProperty(HeadOfficeAddressProperty, value); }
    }

    public static readonly PropertyInfo<bool> IsPriceRequestedProperty = RegisterProperty<bool>(c => c.IsPriceRequested);
    public bool IsPriceRequested
    {
        get { return GetProperty(IsPriceRequestedProperty); }
        set { SetProperty(IsPriceRequestedProperty, value); }
    }

    public static readonly PropertyInfo<bool> IsNewOrderHoldedProperty = RegisterProperty<bool>(c => c.IsNewOrderHolded);
    public bool IsNewOrderHolded
    {
        get { return GetProperty(IsNewOrderHoldedProperty); }
        set { SetProperty(IsNewOrderHoldedProperty, value); }
    }
    public static readonly PropertyInfo<bool> IsSetupFeesBilledProperty = RegisterProperty<bool>(c => c.IsSetupFeesBilled);
    public bool IsSetupFeesBilled
    {
        get { return GetProperty(IsSetupFeesBilledProperty); }
        set { SetProperty(IsSetupFeesBilledProperty, value); }
    }
    public static readonly PropertyInfo<bool> IsInterestsBilledProperty = RegisterProperty<bool>(c => c.IsInterestsBilled);
    public bool IsInterestsBilled
    {
        get { return GetProperty(IsInterestsBilledProperty); }
        set { SetProperty(IsInterestsBilledProperty, value); }
    }

    public static readonly PropertyInfo<decimal> CreditLimitProperty = RegisterProperty<decimal>(c => c.CreditLimit);
    public decimal CreditLimit
    {
        get { return GetProperty(CreditLimitProperty); }
        set
        {
            SetProperty(CreditLimitProperty, value);
            this.CreditLimitUpdatedOn = DateTime.Now;
            this.CreditLimitUpdatedBy = Csla.ApplicationContext.User.Identity.Name;
        }
    }
    public static readonly PropertyInfo<DateTime?> CreditLimitUpdatedOnProperty = RegisterProperty<DateTime?>(c => c.CreditLimitUpdatedOn);
    public DateTime? CreditLimitUpdatedOn
    {
        get { return GetProperty(CreditLimitUpdatedOnProperty); }
        private set { SetProperty(CreditLimitUpdatedOnProperty, value); }
    }
    public static readonly PropertyInfo<string> CreditLimitUpdatedByProperty = RegisterProperty<string>(c => c.CreditLimitUpdatedBy);
    public string CreditLimitUpdatedBy
    {
        get { return GetProperty(CreditLimitUpdatedByProperty); }
        private set { SetProperty(CreditLimitUpdatedByProperty, value); }
    }

    public static readonly PropertyInfo<decimal> HighestBalanceDueProperty = RegisterProperty<decimal>(c => c.HighestBalanceDue);
    public decimal HighestBalanceDue
    {
        get { return GetProperty(HighestBalanceDueProperty); }
        private set { SetProperty(HighestBalanceDueProperty, value); }
    }
    public static readonly PropertyInfo<DateTime?> HighestBalanceDueDateProperty = RegisterProperty<DateTime?>(c => c.HighestBalanceDueDate);
    public DateTime? HighestBalanceDueDate
    {
        get { return GetProperty(HighestBalanceDueDateProperty); }
        private set { SetProperty(HighestBalanceDueDateProperty, value); }
    }

    public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.Currency> CurrencyProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.Currency>(c => c.Currency);
    public MF_MasterFile.LightBusinessObjects.Currency Currency
    {
        get { return GetProperty(CurrencyProperty); }
        set { SetProperty(CurrencyProperty, value); }
    }

    public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.PaymentTerm> PaymentTermProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.PaymentTerm>(c => c.PaymentTerm);
    public MF_MasterFile.LightBusinessObjects.PaymentTerm PaymentTerm
    {
        get { return GetProperty(PaymentTermProperty); }
        set
        {
            SetProperty(PaymentTermProperty, value);
            this.PaymentTermUpdatedOn = DateTime.Now;
            this.PaymentTermUpdatedBy = Csla.ApplicationContext.User.Identity.Name;
        }
    }
    public static readonly PropertyInfo<DateTime?> PaymentTermUpdatedOnProperty = RegisterProperty<DateTime?>(c => c.PaymentTermUpdatedOn);
    public DateTime? PaymentTermUpdatedOn
    {
        get { return GetProperty(PaymentTermUpdatedOnProperty); }
        private set { SetProperty(PaymentTermUpdatedOnProperty, value); }
    }
    public static readonly PropertyInfo<string> PaymentTermUpdatedByProperty = RegisterProperty<string>(c => c.PaymentTermUpdatedBy);
    public string PaymentTermUpdatedBy
    {
        get { return GetProperty(PaymentTermUpdatedByProperty); }
        private set { SetProperty(PaymentTermUpdatedByProperty, value); }
    }

    public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.Collector> CollectorProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.Collector>(c => c.Collector);
    public MF_MasterFile.LightBusinessObjects.Collector Collector
    {
        get { return GetProperty(CollectorProperty); }
        set { SetProperty(CollectorProperty, value); }
    }

    public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.SalesRepresentative> SalesRepresentativeProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.SalesRepresentative>(c => c.SalesRepresentative);
    public MF_MasterFile.LightBusinessObjects.SalesRepresentative SalesRepresentative
    {
        get { return GetProperty(SalesRepresentativeProperty); }
        set { SetProperty(SalesRepresentativeProperty, value); }
    }

    public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.Language> LanguageProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.Language>(c => c.Language);
    public MF_MasterFile.LightBusinessObjects.Language Language
    {
        get { return GetProperty(LanguageProperty); }
        set { SetProperty(LanguageProperty, value); }
    }

    public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.CustomerType> CustomerTypeProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.CustomerType>(c => c.CustomerType);
    public MF_MasterFile.LightBusinessObjects.CustomerType CustomerType
    {
        get { return GetProperty(CustomerTypeProperty); }
        set { SetProperty(CustomerTypeProperty, value); }
    }

    public static readonly PropertyInfo<string> IRSTaxIDNumberProperty = RegisterProperty<string>(c => c.IRSTaxIDNumber);
    public string IRSTaxIDNumber
    {
        get { return GetProperty(IRSTaxIDNumberProperty); }
        set { SetProperty(IRSTaxIDNumberProperty, value); }
    }

    public static readonly PropertyInfo<decimal> PublicityDiscountProperty = RegisterProperty<decimal>(c => c.PublicityDiscount);
    public decimal PublicityDiscount
    {
        get { return GetProperty(PublicityDiscountProperty); }
        set { SetProperty(PublicityDiscountProperty, value); }
    }

    public static readonly PropertyInfo<DateTime?> PublicityDiscountUpdatedOnProperty = RegisterProperty<DateTime?>(c => c.PublicityDiscountUpdatedOn);
    public DateTime? PublicityDiscountUpdatedOn
    {
        get { return GetProperty(PublicityDiscountUpdatedOnProperty); }
        set { SetProperty(PublicityDiscountUpdatedOnProperty, value); }
    }

    public static readonly PropertyInfo<string> PublicityDiscountUpdatedByProperty = RegisterProperty<string>(c => c.PublicityDiscountUpdatedBy);
    public string PublicityDiscountUpdatedBy
    {
        get { return GetProperty(PublicityDiscountUpdatedByProperty); }
        set { SetProperty(PublicityDiscountUpdatedByProperty, value); }
    }

    public static readonly PropertyInfo<decimal> ShipmentDiscountProperty = RegisterProperty<decimal>(c => c.ShipmentDiscount);
    public decimal ShipmentDiscount
    {
        get { return GetProperty(ShipmentDiscountProperty); }
        set { SetProperty(ShipmentDiscountProperty, value); }
    }

    public static readonly PropertyInfo<DateTime?> ShipmentDiscountUpdatedOnProperty = RegisterProperty<DateTime?>(c => c.ShipmentDiscountUpdatedOn);
    public DateTime? ShipmentDiscountUpdatedOn
    {
        get { return GetProperty(ShipmentDiscountUpdatedOnProperty); }
        set { SetProperty(ShipmentDiscountUpdatedOnProperty, value); }
    }

    public static readonly PropertyInfo<string> ShipmentDiscountUpdatedByProperty = RegisterProperty<string>(c => c.ShipmentDiscountUpdatedBy);
    public string ShipmentDiscountUpdatedBy
    {
        get { return GetProperty(ShipmentDiscountUpdatedByProperty); }
        set { SetProperty(ShipmentDiscountUpdatedByProperty, value); }
    }

    public static readonly PropertyInfo<decimal> OtherDiscountProperty = RegisterProperty<decimal>(c => c.OtherDiscount);
    public decimal OtherDiscount
    {
        get { return GetProperty(OtherDiscountProperty); }
        set { SetProperty(OtherDiscountProperty, value); }
    }

    public static readonly PropertyInfo<DateTime?> OtherDiscountUpdatedOnProperty = RegisterProperty<DateTime?>(c => c.OtherDiscountUpdatedOn);
    public DateTime? OtherDiscountUpdatedOn
    {
        get { return GetProperty(OtherDiscountUpdatedOnProperty); }
        set { SetProperty(OtherDiscountUpdatedOnProperty, value); }
    }

    public static readonly PropertyInfo<string> OtherDiscountUpdatedByProperty = RegisterProperty<string>(c => c.OtherDiscountUpdatedBy);
    public string OtherDiscountUpdatedBy
    {
        get { return GetProperty(OtherDiscountUpdatedByProperty); }
        set { SetProperty(OtherDiscountUpdatedByProperty, value); }
    }

    public static readonly PropertyInfo<bool> FlagVolumeDiscountProperty = RegisterProperty<bool>(c => c.FlagVolumeDiscount);
    public bool FlagVolumeDiscount
    {
        get { return GetProperty(FlagVolumeDiscountProperty); }
        set { SetProperty(FlagVolumeDiscountProperty, value); }
    }

    public static readonly PropertyInfo<string> OtherSalesConditionsProperty = RegisterProperty<string>(c => c.OtherSalesConditions);
    public string OtherSalesConditions
    {
        get { return GetProperty(OtherSalesConditionsProperty); }
        set { SetProperty(OtherSalesConditionsProperty, value); }
    }

    public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.TransmissionMode> PriceListTrxModeProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.TransmissionMode>(c => c.PriceListTrxMode);
    public MF_MasterFile.LightBusinessObjects.TransmissionMode PriceListTrxMode
    {
        get { return GetProperty(PriceListTrxModeProperty); }
        set { SetProperty(PriceListTrxModeProperty, value); }
    }
    public static readonly PropertyInfo<Customer._Contact> PriceListContactProperty = RegisterProperty<Customer._Contact>(c => c.PriceListContact);
    public Customer._Contact PriceListContact
    {
        get { return GetProperty(PriceListContactProperty); }
        set { SetProperty(PriceListContactProperty, value); }
    }
    public static readonly PropertyInfo<DateTime?> PriceListLastSentDateProperty = RegisterProperty<DateTime?>(c => c.PriceListLastSentDate);
    public DateTime? PriceListLastSentDate
    {
        get { return GetProperty(PriceListLastSentDateProperty); }
        set { SetProperty(PriceListLastSentDateProperty, value); }
    }

    public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.TransmissionMode> OrderConfirmationTrxModeProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.TransmissionMode>(c => c.OrderConfirmationTrxMode);
    public MF_MasterFile.LightBusinessObjects.TransmissionMode OrderConfirmationTrxMode
    {
        get { return GetProperty(OrderConfirmationTrxModeProperty); }
        set { SetProperty(OrderConfirmationTrxModeProperty, value); }
    }
    public static readonly PropertyInfo<Customer._Contact> OrderConfirmationContactProperty = RegisterProperty<Customer._Contact>(c => c.OrderConfirmationContact);
    public Customer._Contact OrderConfirmationContact
    {
        get { return GetProperty(OrderConfirmationContactProperty); }
        set { SetProperty(OrderConfirmationContactProperty, value); }
    }
    public static readonly PropertyInfo<DateTime?> OrderConfirmationLastSentDateProperty = RegisterProperty<DateTime?>(c => c.OrderConfirmationLastSentDate);
    public DateTime? OrderConfirmationLastSentDate
    {
        get { return GetProperty(OrderConfirmationLastSentDateProperty); }
        set { SetProperty(OrderConfirmationLastSentDateProperty, value); }
    }

    public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.TransmissionMode> InvoiceTrxModeProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.TransmissionMode>(c => c.InvoiceTrxMode);
    public MF_MasterFile.LightBusinessObjects.TransmissionMode InvoiceTrxMode
    {
        get { return GetProperty(InvoiceTrxModeProperty); }
        set { SetProperty(InvoiceTrxModeProperty, value); }
    }
    public static readonly PropertyInfo<Customer._Contact> InvoiceContactProperty = RegisterProperty<Customer._Contact>(c => c.InvoiceContact);
    public Customer._Contact InvoiceContact
    {
        get { return GetProperty(InvoiceContactProperty); }
        set { SetProperty(InvoiceContactProperty, value); }
    }
    public static readonly PropertyInfo<DateTime?> InvoiceLastSentDateProperty = RegisterProperty<DateTime?>(c => c.InvoiceLastSentDate);
    public DateTime? InvoiceLastSentDate
    {
        get { return GetProperty(InvoiceLastSentDateProperty); }
        set { SetProperty(InvoiceLastSentDateProperty, value); }
    }

    public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.TransmissionMode> StatementTrxModeProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.TransmissionMode>(c => c.StatementTrxMode);
    public MF_MasterFile.LightBusinessObjects.TransmissionMode StatementTrxMode
    {
        get { return GetProperty(StatementTrxModeProperty); }
        set { SetProperty(StatementTrxModeProperty, value); }
    }
    public static readonly PropertyInfo<Customer._Contact> StatementContactProperty = RegisterProperty<Customer._Contact>(c => c.StatementContact);
    public Customer._Contact StatementContact
    {
        get { return GetProperty(StatementContactProperty); }
        set { SetProperty(StatementContactProperty, value); }
    }
    public static readonly PropertyInfo<DateTime?> StatementLastSentDateProperty = RegisterProperty<DateTime?>(c => c.StatementLastSentDate);
    public DateTime? StatementLastSentDate
    {
        get { return GetProperty(StatementLastSentDateProperty); }
        set { SetProperty(StatementLastSentDateProperty, value); }
    }

    public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.TransmissionMode> CommunicationTrxModeProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.TransmissionMode>(c => c.CommunicationTrxMode);
    public MF_MasterFile.LightBusinessObjects.TransmissionMode CommunicationTrxMode
    {
        get { return GetProperty(CommunicationTrxModeProperty); }
        set { SetProperty(CommunicationTrxModeProperty, value); }
    }
    public static readonly PropertyInfo<Customer._Contact> CommunicationContactProperty = RegisterProperty<Customer._Contact>(c => c.CommunicationContact);
    public Customer._Contact CommunicationContact
    {
        get { return GetProperty(CommunicationContactProperty); }
        set { SetProperty(CommunicationContactProperty, value); }
    }
    public static readonly PropertyInfo<DateTime?> CommunicationLastSentDateProperty = RegisterProperty<DateTime?>(c => c.CommunicationLastSentDate);
    public DateTime? CommunicationLastSentDate
    {
        get { return GetProperty(CommunicationLastSentDateProperty); }
        set { SetProperty(CommunicationLastSentDateProperty, value); }
    }

    public static readonly PropertyInfo<DateTime?> CreationDateProperty = RegisterProperty<DateTime?>(c => c.CreationDate);
    public DateTime? CreationDate
    {
        get { return GetProperty(CreationDateProperty); }
        private set { SetProperty(CreationDateProperty, value); }
    }
    public static readonly PropertyInfo<string> CreationUserProperty = RegisterProperty<string>(c => c.CreationUser);
    public string CreationUser
    {
        get { return GetProperty(CreationUserProperty); }
        private set { SetProperty(CreationUserProperty, value); }
    }

    public static readonly PropertyInfo<DateTime?> LastModificationDateProperty = RegisterProperty<DateTime?>(c => c.LastModificationDate);
    public DateTime? LastModificationDate
    {
        get { return GetProperty(LastModificationDateProperty); }
        private set { SetProperty(LastModificationDateProperty, value); }
    }
    public static readonly PropertyInfo<string> LastModificationUserProperty = RegisterProperty<string>(c => c.LastModificationUser);
    public string LastModificationUser
    {
        get { return GetProperty(LastModificationUserProperty); }
        private set { SetProperty(LastModificationUserProperty, value); }
    }

    public static readonly PropertyInfo<byte[]> RowTimestampProperty = RegisterProperty<byte[]>(c => c.RowTimestamp);
    public byte[] RowTimestamp
    {
        get { return GetProperty(RowTimestampProperty); }
        private set { LoadProperty(RowTimestampProperty, value); }
    }

    #endregion

    #region Child Properties

    public static readonly PropertyInfo<Customer._AddressCollection> AddressesProperty = RegisterProperty<Customer._AddressCollection>(c => c.Addresses, RelationshipTypes.Child);
    public Customer._AddressCollection Addresses
    {
        get { return GetProperty(AddressesProperty); }
        private set { SetProperty(AddressesProperty, value); }
    }

    public static readonly PropertyInfo<Customer._ContactCollection> ContactsProperty = RegisterProperty<Customer._ContactCollection>(c => c.Contacts, "Contacts", null, RelationshipTypes.Child | RelationshipTypes.LazyLoad);
    public Customer._ContactCollection Contacts
    {
        get
        {
            if (!FieldManager.FieldExists(ContactsProperty))
            {
                if (this.IsNew)
                    this.Contacts = DataPortal.CreateChild<Customer._ContactCollection>();
                else
                    this.Contacts = Customer._ContactCollection.FetchChildren(this);
            }
            return GetProperty(ContactsProperty);
        }
        private set
        {
            LoadProperty(ContactsProperty, value);
            OnPropertyChanged(ContactsProperty);
        }
    }

    public static readonly PropertyInfo<Customer._NoteCollection> NotesProperty = RegisterProperty<Customer._NoteCollection>(c => c.Notes, RelationshipTypes.Child);
    public Customer._NoteCollection Notes
    {
        get { return GetProperty(NotesProperty); }
        private set { SetProperty(NotesProperty, value); }
    }

    //public static readonly PropertyInfo<Customer._VolumeDiscountCollection> VolumeDiscountsProperty = RegisterProperty<Customer._VolumeDiscountCollection>(c => c.VolumeDiscounts, RelationshipTypes.Child);
    //public Customer._VolumeDiscountCollection VolumeDiscounts
    //{
    //    get { return GetProperty(VolumeDiscountsProperty); }
    //    private set { SetProperty(VolumeDiscountsProperty, value); }
    //}

    #endregion

    #endregion

    #region Search Functions

    #region GetCustomer

    [Serializable]
    internal class GetCustomerByKeyCriteria : CriteriaBase<GetCustomerByKeyCriteria>, Customer.ISearchCriteria
    {
        public long ID { get; set; }
        public string Collation { get; set; }
        public Expression<Func<Models.MF_Customer.Customer, bool>> GetWhereExpression()
        {
            return (x => x.ID == this.ID);
        }
        public GetCustomerByKeyCriteria(long id, string collation)
        {
            this.ID = id;
            this.Collation = collation;
        }
    }
    public static Customer GetCustomer(long id, string collation)
    {
        return DataPortal.Fetch<Customer>(new GetCustomerByKeyCriteria(id, collation));
    }
    public static Task<Customer> GetCustomerAsync(long id, string collation)
    {
        return DataPortal.FetchAsync<Customer>(new GetCustomerByKeyCriteria(id, collation));
    }

    #endregion

    #region GetCustomerByCode

    [Serializable]
    internal class GetCustomerByCodeCriteria : CriteriaBase<GetCustomerByCodeCriteria>, Customer.ISearchCriteria
    {
        public string Code { get; set; }
        public string Collation { get; set; }
        public Expression<Func<Models.MF_Customer.Customer, bool>> GetWhereExpression()
        {
            return (x => x.Code == this.Code);
        }
        public GetCustomerByCodeCriteria(string code, string collation)
        {
            this.Code = code;
            this.Collation = collation;
        }
    }
    public static Customer GetCustomerByCode(string code, string collation)
    {
        return DataPortal.Fetch<Customer>(new GetCustomerByCodeCriteria(code, collation));
    }
    public static Task<Customer> GetCustomerByCodeAsync(string code, string collation)
    {
        return DataPortal.FetchAsync<Customer>(new GetCustomerByCodeCriteria(code, collation));
    }

    #endregion

    #region GetSpecificCustomer

    [Serializable]
    internal class GetSpecificCustomerAsyncCriteria : CriteriaBase<GetSpecificCustomerAsyncCriteria>, Customer.ISearchCriteria
    {
        public long ID { get; set; }
        public byte[] RowVersion { get; set; }
        public string Collation { get; set; }
        public Expression<Func<Models.MF_Customer.Customer, bool>> GetWhereExpression()
        {
            return (x => x.ID == this.ID && x.RowTimestamp == this.RowVersion);
        }
        public GetSpecificCustomerAsyncCriteria(long id, byte[] rowVersion, string collation)
        {
            this.ID = id;
            this.RowVersion = rowVersion;
            this.Collation = collation;
        }
    }
    public static Customer GetSpecificCustomer(long id, byte[] rowVersion, string collation)
    {
        return DataPortal.Fetch<Customer>(new GetSpecificCustomerAsyncCriteria(id, rowVersion, collation));
    }
    public static Task<Customer> GetSpecificCustomerAsync(long id, byte[] rowVersion, string collation)
    {
        return DataPortal.FetchAsync<Customer>(new GetSpecificCustomerAsyncCriteria(id, rowVersion, collation));
    }

    #endregion

    #endregion

    #region Model Mappings

    private void FillObjectFromModel(Models.MF_Customer.Customer model)
    {
        using (BypassPropertyChecks)
        {
            LoadProperty(IDProperty, model.ID);
            LoadProperty(AddressesProperty, Customer._AddressCollection.FetchChildren(this.ID, this.DefaultCollation));
            LoadProperty(NotesProperty, Customer._NoteCollection.FetchChildren(this));
            //LoadProperty(ContactsProperty, Customer._ContactCollection.FetchChildren(this.ID, this.DefaultCollation));
            LoadProperty(CodeProperty, model.Code);
            LoadProperty(NameProperty, model.Name);
            LoadProperty(IsActiveProperty, model.IsActive);
            LoadProperty(HeadOfficeAddressProperty, Customer._Address.Fetch(model.HeadOfficeAddressID, model.AddressHeadOffice, this.DefaultCollation));
            LoadProperty(IsNewOrderHoldedProperty, model.IsNewOrderHolded);
            LoadProperty(IsPriceRequestedProperty, model.IsPriceRequested);
            LoadProperty(IsSetupFeesBilledProperty, model.IsSetupFeesBilled);
            LoadProperty(IsInterestsBilledProperty, model.IsInterestBilled);
            LoadProperty(CreditLimitProperty, model.CreditLimit);
            LoadProperty(CreditLimitUpdatedOnProperty, model.CreditLimitUpdatedOn);
            LoadProperty(CreditLimitUpdatedByProperty, model.CreditLimitUpdatedby);
            LoadProperty(HighestBalanceDueProperty, model.HighestBalanceDueAmount);
            LoadProperty(HighestBalanceDueDateProperty, model.HighestBalanceDueAmountUpdatedOn);
            LoadProperty(CurrencyProperty, MF_MasterFile.LightBusinessObjects.Currency.Fetch(model.CurrencyID, model.Currency, this.DefaultCollation));
            LoadProperty(PaymentTermProperty, MF_MasterFile.LightBusinessObjects.PaymentTerm.Fetch(model.PaymentTermID, model.PaymentTerm, this.DefaultCollation));
            LoadProperty(PaymentTermUpdatedOnProperty, model.PaymentTermUpdatedOn);
            LoadProperty(PaymentTermUpdatedByProperty, model.PaymentTermUpdatedBy);
            LoadProperty(CollectorProperty, MF_MasterFile.LightBusinessObjects.Collector.Fetch(model.CollectorID, model.CustomerCollector, this.DefaultCollation));
            LoadProperty(SalesRepresentativeProperty, MF_MasterFile.LightBusinessObjects.SalesRepresentative.Fetch(model.SalesRepresentativeID, model.SalesRepresentative, this.DefaultCollation));
            LoadProperty(LanguageProperty, MF_MasterFile.LightBusinessObjects.Language.Fetch(model.LanguageID, model.Language, this.DefaultCollation));
            LoadProperty(CustomerTypeProperty, MF_MasterFile.LightBusinessObjects.CustomerType.Fetch(model.CustomerTypeID, model.CustomerType, this.DefaultCollation));
            LoadProperty(IRSTaxIDNumberProperty, model.IRSTaxIDNumber);
            LoadProperty(PublicityDiscountProperty, model.PublicityDiscount);
            LoadProperty(PublicityDiscountUpdatedOnProperty, model.PublicityDiscountUpdatedOn);
            LoadProperty(PublicityDiscountUpdatedByProperty, model.PublicityDiscountUpdatedBy);
            LoadProperty(ShipmentDiscountProperty, model.ShipmentDiscount);
            LoadProperty(ShipmentDiscountUpdatedOnProperty, model.ShipmentDiscountUpdatedOn);
            LoadProperty(ShipmentDiscountUpdatedByProperty, model.ShipmentDiscountUpdatedBy);
            LoadProperty(OtherDiscountProperty, model.OtherDiscount);
            LoadProperty(OtherDiscountUpdatedOnProperty, model.OtherDiscountUpdatedOn);
            LoadProperty(OtherDiscountUpdatedByProperty, model.OtherDiscountUpdatedBy);
            LoadProperty(FlagVolumeDiscountProperty, model.FlagVolumeDiscount);
            LoadProperty(OtherSalesConditionsProperty, model.OtherSalesConditions);
            LoadProperty(PriceListTrxModeProperty, MF_MasterFile.LightBusinessObjects.TransmissionMode.Fetch(model.PriceListTransmissionModeID, model.TransmissionModePriceList, this.DefaultCollation));
            //LoadProperty(PriceListContactProperty, (model.PriceListTransmissionContactID != null ? this.Contacts.SingleOrDefault(x => x.ID == model.PriceListTransmissionContactID) : null));
            LoadProperty(PriceListLastSentDateProperty, model.PriceListTransmissionDate);
            LoadProperty(OrderConfirmationTrxModeProperty, MF_MasterFile.LightBusinessObjects.TransmissionMode.Fetch(model.OrderConfirmationTransmissionModeID, model.TransmissionModeOrderConfirmation, this.DefaultCollation));
           // LoadProperty(OrderConfirmationContactProperty, (model.OrderConfirmationTransmissionContactID != null ? this.Contacts.SingleOrDefault(x => x.ID == model.OrderConfirmationTransmissionContactID) : null));
            LoadProperty(OrderConfirmationLastSentDateProperty, model.OrderConfirmationTransmissionDate);
            LoadProperty(InvoiceTrxModeProperty, MF_MasterFile.LightBusinessObjects.TransmissionMode.Fetch(model.InvoiceTransmissionModeID, model.TransmissionModeInvoice, this.DefaultCollation));
           // LoadProperty(InvoiceContactProperty, (model.InvoiceTransmissionContactID != null ? this.Contacts.SingleOrDefault(x => x.ID == model.InvoiceTransmissionContactID) : null));
            LoadProperty(InvoiceLastSentDateProperty, model.InvoiceTransmissionDate);
            LoadProperty(StatementTrxModeProperty, MF_MasterFile.LightBusinessObjects.TransmissionMode.Fetch(model.StatementTransmissionModeID, model.TransmissionModeStatement, this.DefaultCollation));
            //LoadProperty(StatementContactProperty, (model.StatementTransmissionContactID != null ? this.Contacts.SingleOrDefault(x => x.ID == model.StatementTransmissionContactID) : null));
            LoadProperty(StatementLastSentDateProperty, model.StatementTransmissionDate);
            LoadProperty(CommunicationTrxModeProperty, MF_MasterFile.LightBusinessObjects.TransmissionMode.Fetch(model.CommunicationsTransmissionModeID, model.TransmissionModeCommunications, this.DefaultCollation));
            //LoadProperty(CommunicationContactProperty, (model.CommunicationsTransmissionContactID != null ? this.Contacts.SingleOrDefault(x => x.ID == model.CommunicationsTransmissionContactID) : null));
            LoadProperty(CommunicationLastSentDateProperty, model.CommunicationsTransmissionDate);
            LoadProperty(CreationDateProperty, model.CreationDate);
            LoadProperty(CreationUserProperty, model.CreationUser);
            LoadProperty(LastModificationDateProperty, model.LastModificationDate);
            LoadProperty(LastModificationUserProperty, model.LastModificationUser);
            LoadProperty(RowTimestampProperty, model.RowTimestamp);

            //LoadProperty(VolumeDiscountsProperty, Customer._VolumeDiscountCollection.FetchChildren(this));
        }
    }

    private void FillModelFromObject(Models.MF_Customer.Customer model)
    {
        model.Code = this.Code;
        model.Name = this.Name;
        model.IsActive = this.IsActive;
        model.HeadOfficeAddressID = this.HeadOfficeAddress.ID;
        model.IsNewOrderHolded = this.IsNewOrderHolded;
        model.IsPriceRequested = this.IsPriceRequested;
        model.IsSetupFeesBilled = this.IsSetupFeesBilled;
        model.IsInterestBilled = this.IsInterestsBilled;
        model.CreditLimit = this.CreditLimit;
        model.CreditLimitUpdatedOn = this.CreditLimitUpdatedOn;
        model.CreditLimitUpdatedby = this.CreditLimitUpdatedBy;
        model.HighestBalanceDueAmount = this.HighestBalanceDue;
        model.HighestBalanceDueAmountUpdatedOn = this.HighestBalanceDueDate;
        model.CurrencyID = this.Currency.ID;
        model.PaymentTermID = this.PaymentTerm.ID;
        model.PaymentTermUpdatedOn = this.PaymentTermUpdatedOn;
        model.PaymentTermUpdatedBy = this.PaymentTermUpdatedBy;
        model.CollectorID = this.Collector.ID;
        model.SalesRepresentativeID = this.SalesRepresentative != null ? this.SalesRepresentative.ID : (long?)null;
        model.LanguageID = this.Language.ID;
        model.CustomerTypeID = this.CustomerType.ID;
        model.IRSTaxIDNumber = this.IRSTaxIDNumber;
        model.PublicityDiscount = this.PublicityDiscount;
        model.PublicityDiscountUpdatedOn = this.PublicityDiscountUpdatedOn;
        model.PublicityDiscountUpdatedBy = this.PublicityDiscountUpdatedBy;
        model.ShipmentDiscount = this.ShipmentDiscount;
        model.ShipmentDiscountUpdatedOn = this.ShipmentDiscountUpdatedOn;
        model.ShipmentDiscountUpdatedBy = this.ShipmentDiscountUpdatedBy;
        model.OtherDiscount = this.OtherDiscount;
        model.OtherDiscountUpdatedOn = this.OtherDiscountUpdatedOn;
        model.OtherDiscountUpdatedBy = this.OtherDiscountUpdatedBy;
        model.FlagVolumeDiscount = this.FlagVolumeDiscount;
        model.OtherSalesConditions = this.OtherSalesConditions;
        model.PriceListTransmissionModeID = this.PriceListTrxMode.ID;
        model.PriceListTransmissionDate = this.PriceListLastSentDate;
        model.PriceListTransmissionContactID = this.PriceListContact != null ? this.PriceListContact.ID : (long?)null;
        model.OrderConfirmationTransmissionModeID = this.OrderConfirmationTrxMode.ID;
        model.OrderConfirmationTransmissionDate = this.OrderConfirmationLastSentDate;
        model.OrderConfirmationTransmissionContactID = this.OrderConfirmationContact != null ? this.OrderConfirmationContact.ID : (long?)null;
        model.InvoiceTransmissionModeID = this.InvoiceTrxMode.ID;
        model.InvoiceTransmissionDate = this.InvoiceLastSentDate;
        model.InvoiceTransmissionContactID = this.InvoiceContact != null ? this.InvoiceContact.ID : (long?)null;
        model.StatementTransmissionModeID = this.StatementTrxMode.ID;
        model.StatementTransmissionDate = this.StatementLastSentDate;
        model.StatementTransmissionContactID = this.StatementContact != null ? this.StatementContact.ID : (long?)null;
        model.CommunicationsTransmissionModeID = this.CommunicationTrxMode.ID;
        model.CommunicationsTransmissionDate = this.CommunicationLastSentDate;
        model.CommunicationsTransmissionContactID = this.CommunicationContact != null ? this.CommunicationContact.ID : (long?)null;
        model.CreationDate = null;
        model.CreationUser = null;
        model.LastModificationDate = null;
        model.LastModificationUser = null;
    }

    #endregion

    #region DataPortal Functions

    internal class DataPortal_FetchArgs
    {
        public string DefaultCollection { get; set; }
        public Models.MF_Customer.Customer Model { get; set; }
    }
    internal interface ISearchCriteria
    {
        string Collation { get; set; }
        Expression<Func<Models.MF_Customer.Customer, bool>> GetWhereExpression();
    }
    internal static Base.CORE.DataLayer.IDbContextBase DomainDrivenDesignBoundedContext
    {
        get { return new DataLayer.EnterpriseResourcePlanning.CustomerContext(); }
    }

    internal static Expression<Func<Models.MF_Customer.Customer, object>>[] NavigationPropertiesToInclude
    {
        get
        {
            List<Expression<Func<Models.MF_Customer.Customer, object>>> navProperties = new List<Expression<Func<Models.MF_Customer.Customer, object>>>();

            navProperties.Add(x => x.CustomerType);
            navProperties.Add(x => x.Currency);
            navProperties.Add(x => x.PaymentTerm);
            navProperties.Add(x => x.CustomerCollector);
            navProperties.Add(x => x.SalesRepresentative);
            navProperties.Add(x => x.Language);
            navProperties.Add(x => x.TransmissionModePriceList);
            navProperties.Add(x => x.TransmissionModeInvoice);
            navProperties.Add(x => x.TransmissionModeOrderConfirmation);
            navProperties.Add(x => x.TransmissionModeCommunications);
            navProperties.Add(x => x.TransmissionModeStatement);
            navProperties.Add(x => x.ContactPriceList);
            navProperties.Add(x => x.ContactInvoice);
            navProperties.Add(x => x.ContactOrderConfirmation);
            navProperties.Add(x => x.ContactCommunications);
            navProperties.Add(x => x.ContactStatement);
            navProperties.Add(x => x.Address);
            navProperties.Add(x => x.AddressHeadOffice);
            navProperties.Add(x => x.Contact);
            navProperties.Add(x => x.CustomerNote);

            return navProperties.ToArray();
        }
    }

    internal static Customer Fetch(long? id, Models.MF_Customer.Customer model, string collation)
    {
        if (id == null) return null;
        if (model != null) return DataPortal.Fetch<Customer>(new DataPortal_FetchArgs() { Model = model, DefaultCollection = collation });
        return DataPortal.Fetch<Customer>(new GetCustomerByKeyCriteria((long)id, collation));
    }
    internal static Task<Customer> FetchAsync(long? id, Models.MF_Customer.Customer model, string collation)
    {
        if (id == null) return null;
        if (model != null) return DataPortal.FetchAsync<Customer>(new DataPortal_FetchArgs() { Model = model, DefaultCollection = collation });
        return DataPortal.FetchAsync<Customer>(new GetCustomerByKeyCriteria((long)id, collation));
    }

    protected override void DataPortal_Create()
    {
        CreateObject();
    }

    private void CreateObject()
    {
        this.IsActive = true;
        this.CreationDate = System.DateTime.Now;
        this.CreationUser = Csla.ApplicationContext.User.Identity.Name;

        if (this.Addresses == null)
            this.Addresses = DataPortal.CreateChild<Customer._AddressCollection>();

        if (this.Notes == null)
            this.Notes = DataPortal.CreateChild<Customer._NoteCollection>();
    }

    private void DataPortal_Fetch(ISearchCriteria criteria)
    {
        FetchModel(criteria);
    }
    private void Child_Fetch(ISearchCriteria criteria)
    {
        FetchModel(criteria);
    }
    private void FetchModel(ISearchCriteria criteria)
    {
        using (Base.CORE.DataLayer.IDbContextBase _context = DomainDrivenDesignBoundedContext)
        {
            //Selecting + Including
            var query = _context.GetQuery<Models.MF_Customer.Customer>(Customer.NavigationPropertiesToInclude);

            // Filtering
            if (criteria.GetWhereExpression() != null)
                query = query.Where(criteria.GetWhereExpression());

            // Executing
            var model = query.Single();
            if (model != null)
            {
                // Building
                DataPortal_FetchArgs args = new DataPortal_FetchArgs() { Model = model, DefaultCollection = criteria.Collation };
                FetchModel(args);
            }
        }
    }

    private void DataPortal_Fetch(DataPortal_FetchArgs args)
    {
        FetchModel(args);
    }
    private void Child_Fetch(DataPortal_FetchArgs args)
    {
        FetchModel(args);
    }
    private void FetchModel(DataPortal_FetchArgs args)
    {
        this.DefaultCollation = args.DefaultCollection;
        FillObjectFromModel(args.Model);
    }

    protected override void DataPortal_Insert() { InsertModel(); }
    private void Child_Insert() { InsertModel(); }
    private void InsertModel()
    {
        using (Base.CORE.DataLayer.IDbContextBase _context = DomainDrivenDesignBoundedContext)
        {
            var query = from o in _context.GetQuery<Models.MF_Customer.Customer>()
                        where o.Code == this.Code
                        select o;
            if (query.Count() > 0)
                throw new DataPortalException("Code already exists", this);

            Models.MF_Customer.Customer model = new Models.MF_Customer.Customer();
            FillModelFromObject(model);

            _context.Add<Models.MF_Customer.Customer>(model);
            _context.SaveChanges();

            this.ID = model.ID;
            DataPortal.UpdateChild(this.Addresses);
            DataPortal.UpdateChild(this.Contacts);
            DataPortal.UpdateChild(this.Notes);

            FetchModel(new GetCustomerByKeyCriteria(model.ID, this.DefaultCollation));
        }
    }

    protected override void DataPortal_Update() { UpdateModel(); }
    private void Child_Update() { UpdateModel(); }
    private void UpdateModel()
    {
        using (Base.CORE.DataLayer.IDbContextBase _context = DomainDrivenDesignBoundedContext)
        {
            var query = from o in _context.GetQuery<Models.MF_Customer.Customer>()
                        where o.ID == this.ID
                        where o.RowTimestamp == this.RowTimestamp
                        select o;

            var model = query.SingleOrDefault();
            if (model == null)
                throw new DataPortalException("ConcurrencyCheck Failed", this);

            FillModelFromObject(model);

            _context.Update<Models.MF_Customer.Customer>(model);
            _context.SaveChanges();

            this.ID = model.ID;
            DataPortal.UpdateChild(this.Addresses);
            DataPortal.UpdateChild(this.Contacts);
            DataPortal.UpdateChild(this.Notes);

            FetchModel(new GetCustomerByKeyCriteria(model.ID, this.DefaultCollation));
        }
    }

    protected override void DataPortal_DeleteSelf() { DeleteModel(); }
    private void Child_DeleteSelf() { DeleteModel(); }
    private void DeleteModel()
    {
        using (Base.CORE.DataLayer.IDbContextBase _context = DomainDrivenDesignBoundedContext)
        {
            var query = from o in _context.GetQuery<Models.MF_Customer.Customer>()
                        where o.ID == this.ID
                        where o.RowTimestamp == this.RowTimestamp
                        select o;

            var model = query.SingleOrDefault();
            if (model == null)
                throw new DataPortalException("ConcurrencyCheck Failed", this);

            this.Addresses.Clear();
            DataPortal.UpdateChild(this.Addresses);

            this.Contacts.Clear();
            DataPortal.UpdateChild(this.Contacts);

            this.Notes.Clear();
            DataPortal.UpdateChild(this.Notes);

            _context.Delete<Models.MF_Customer.Customer>(model);
            _context.SaveChanges();
        }
    }

    #endregion

    #region Validation

    protected override void AddBusinessRules()
    {
        base.AddBusinessRules();

        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(CodeProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientCodeProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(NameProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientNameProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(Address1Property) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientAddress1Property_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(CityProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientCityProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(ProvinceProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientProvinceProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(CountryProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientCountryProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(PostalCodeProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientPostalCodeProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(ActivityStateProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientActivityStateProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(HoldEveryNewOrderProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientHoldEveryNewOrderProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(IsSetupFeesBilledProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientIsSetupFeesBilledProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(IsInterestsBilledProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientIsInterestsBilledProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(CreditLimitProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientCreditLimitProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(HighestBalanceDueProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientHighestBalanceDueProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(CurrencyProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientCurrencyProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(PaymentTermsProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientPaymentTermsProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(CollectorProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientCollectorProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(LanguageProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientLanguageProperty_RequiredRule; }*/ });
        ////BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(CustomerTypeProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientCustomerTypeProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(FlagDeckoProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientFlagDeckoProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(PublicityDiscountFlagIncludingDeckoProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientPublicityDiscountFlagIncludingDeckoProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(ToolSystemDiscountFlagIncludingDeckoProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientToolSystemDiscountFlagIncludingDeckoProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(ShipmentDiscountFlagIncludingDeckoProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientShipmentDiscountFlagIncludingDeckoProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(FlagVolumeDiscountProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientFlagVolumeDiscountProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(FlagVolumeDiscountIncludingDeckoProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientFlagVolumeDiscountIncludingDeckoProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(FlagVolumeDiscountOmniOnlyProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientFlagVolumeDiscountOmniOnlyProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(PriceListTrxModeProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientPriceListTrxModeProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(PriceListContactProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientPriceListContactProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(OrderConfirmationTrxModeProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientOrderConfirmationTrxModeProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(InvoiceTrxModeProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientInvoiceTrxModeProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(StatementTrxModeProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientStatementTrxModeProperty_RequiredRule; }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(CommunicationTrxModeProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.Client_ClientCommunicationTrxModeProperty_RequiredRule; }*/ });

        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(CodeProperty, 32) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.Client_ClientCodeProperty_MaxLengthRule, 32); }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(NameProperty, 256) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.Client_ClientNameProperty_MaxLengthRule, 256); }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(Address1Property, 128) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.Client_ClientAddress1Property_MaxLengthRule, 128); }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(Address2Property, 128) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.Client_ClientAddress2Property_MaxLengthRule, 128); }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(Address3Property, 128) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.Client_ClientAddress3Property_MaxLengthRule, 128); }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(CreditLimitUpdatedByProperty, 256) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.Client_ClientCreditLimitUpdatedByProperty_MaxLengthRule, 256); }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(PaymentTermsUpdatedByProperty, 256) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.Client_ClientPaymentTermsUpdatedByProperty_MaxLengthRule, 256); }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(IRSTaxIDNumberProperty, 128) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.Client_ClientIRSTaxIDNumberProperty_MaxLengthRule, 128); }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(PublicityDiscountUpdatedByProperty, 256) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.Client_ClientPublicityDiscountUpdatedByProperty_MaxLengthRule, 256); }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(ToolSystemDiscountUpdatedByProperty, 256) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.Client_ClientToolSystemDiscountUpdatedByProperty_MaxLengthRule, 256); }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(ShipmentDiscountUpdatedByProperty, 256) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.Client_ClientShipmentDiscountUpdatedByProperty_MaxLengthRule, 256); }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(OtherDiscountUpdatedByProperty, 256) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.Client_ClientOtherDiscountUpdatedByProperty_MaxLengthRule, 256); }*/ });
        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(OtherSalesConditionsProperty, 4096) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.Client_ClientOtherSalesConditionsProperty_MaxLengthRule, 4096); }*/ });
    }

    #endregion

    public static new void SetAsNew(Customer obj)
    {
        obj.MarkNew();
        obj.CreateObject();

        foreach (Customer._Contact item in obj.Contacts)
            Customer._Contact.SetAsNew(item);

        foreach (Customer._Note item in obj.Notes)
            Customer._Note.SetAsNew(item);
    }

    #region One-to-Many Relationship Helper -> _Address

    [Serializable]
    public class _AddressCollection : Base.CORE.BusinessObjects.CustomReadOnlyListBase<_AddressCollection, Customer._Address>
    {
        private _AddressCollection() { /* Require use of factory methods */ }

        #region Search Functions

        [Serializable]
        internal class DefaultSearchCriteria : CriteriaBase<DefaultSearchCriteria>, Customer._Address.ISearchCriteria
        {
            public string SearchValue { get; set; }
            public bool? IsActive { get; set; }
            public string Collation { get; set; }
            public long? CustomerID { get; set; }
            public Expression<Func<Models.MF_Customer.Address, bool>> GetWhereExpression()
            {
                return (x => ((this.SearchValue != null && this.SearchValue.Length > 0) ? (
                                    x.Code.Contains(this.SearchValue)
                                    || x.Name.Contains(this.SearchValue)
                                 ) : true)
                                 && (x.CustomerID == (this.CustomerID != null ? this.CustomerID : null))
                              && (x.IsActive == (this.IsActive != null ? this.IsActive : x.IsActive))
                           );
            }
            public DefaultSearchCriteria(long? customerID, string searchValue, bool? isActive, string collation)
            {
                this.SearchValue = searchValue;
                this.IsActive = isActive;
                this.Collation = collation;
                this.CustomerID = customerID;
            }
        }
        public static Customer._AddressCollection FetchChildren(long? customerID, string collation)
        {
            return DataPortal.Fetch<Customer._AddressCollection>(new DefaultSearchCriteria(customerID, null, null, collation));
        }
        public static Customer._AddressCollection SearchAdressesAsync(string searchValue, bool? isActive, string collation)
        {
            return DataPortal.Fetch<Customer._AddressCollection>(new DefaultSearchCriteria(null, searchValue, isActive, collation));
        }

        #endregion

        #region DataPortal Functions

        private void DataPortal_Fetch(Customer._Address.ISearchCriteria criteria)
        {
            FetchModel(criteria);
        }
        private void Child_Fetch(Customer._Address.ISearchCriteria criteria)
        {
            FetchModel(criteria);
        }
        private void FetchModel(Customer._Address.ISearchCriteria criteria)
        {
            this.IsReadOnly = false;
            var rlce = this.RaiseListChangedEvents;
            this.RaiseListChangedEvents = false;
            {
                using (Base.CORE.DataLayer.IDbContextBase _context = Customer._Address.DomainDrivenDesignBoundedContext)
                {
                    //Selecting + Including
                    var query = _context.GetQuery<Models.MF_Customer.Address>();

                    // Filtering
                    if (criteria.GetWhereExpression() != null)
                        query = query.Where(criteria.GetWhereExpression());

                    // Sorting
                    query = query.OrderBy(x => x.Code).ThenBy(x => x.Name);

                    // Executing
                    List<Models.MF_Customer.Address> list = query.ToList();

                    // Building
                    foreach (Models.MF_Customer.Address model in list)
                        Add(DataPortal.FetchChild<Customer._Address>(new Customer._Address.DataPortal_FetchArgs { Model = model, DefaultCollection = criteria.Collation }));
                }
            }
            this.RaiseListChangedEvents = rlce;
            this.IsReadOnly = true;
        }

        #endregion

        public void AddByAddressID(long id, string collation)
        {
            this.IsReadOnly = false;
            this.Add(DataPortal.FetchChild<Customer._Address>(new Customer._Address.GetAddressByKeyCriteria(id, collation)));
            this.IsReadOnly = true;
        }
        public void RefreshByAddressID(long id, string collation)
        {
            this.IsReadOnly = false;
            this[this.IndexOf(this.Single(x => x.ID == id))] = DataPortal.FetchChild<Customer._Address>(new Customer._Address.GetAddressByKeyCriteria(id, collation));
            this.IsReadOnly = true;
        }
        public void RemoveByAddressID(long id)
        {
            this.IsReadOnly = false;
            this.RemoveAt(this.IndexOf(this.Single(x => x.ID == id)));
            this.IsReadOnly = true;
        }

    }

    [Serializable]
    public class _Address : Base.CORE.BusinessObjects.CustomReadOnlyBase<_Address>
    {
        private _Address() : base() { /* Require use of factory methods */ }

        #region Properties

        #region Root Properties

        public static readonly PropertyInfo<long> IDProperty = RegisterProperty<long>(c => c.ID);
        public long ID
        {
            get { return GetProperty(IDProperty); }
            private set { LoadProperty(IDProperty, value); }
        }

        public static readonly PropertyInfo<string> CodeProperty = RegisterProperty<string>(c => c.Code);
        public string Code
        {
            get { return GetProperty(CodeProperty); }
            private set { LoadProperty(CodeProperty, value); }
        }

        public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(c => c.Name);
        public string Name
        {
            get { return GetProperty(NameProperty); }
            private set { LoadProperty(NameProperty, value); }
        }

        public static readonly PropertyInfo<string> Address1Property = RegisterProperty<string>(c => c.Address1);
        public string Address1
        {
            get { return GetProperty(Address1Property); }
            private set { LoadProperty(Address1Property, value); }
        }

        public static readonly PropertyInfo<string> Address2Property = RegisterProperty<string>(c => c.Address2);
        public string Address2
        {
            get { return GetProperty(Address2Property); }
            private set { LoadProperty(Address2Property, value); }
        }

        public static readonly PropertyInfo<string> Address3Property = RegisterProperty<string>(c => c.Address3);
        public string Address3
        {
            get { return GetProperty(Address3Property); }
            private set { LoadProperty(Address3Property, value); }
        }

        public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.City> CityProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.City>(c => c.City);
        public MF_MasterFile.LightBusinessObjects.City City
        {
            get { return GetProperty(CityProperty); }
            private set { LoadProperty(CityProperty, value); }
        }

        public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.Province> ProvinceProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.Province>(c => c.Province);
        public MF_MasterFile.LightBusinessObjects.Province Province
        {
            get { return GetProperty(ProvinceProperty); }
            private set { LoadProperty(ProvinceProperty, value); }
        }

        public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.Country> CountryProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.Country>(c => c.Country);
        public MF_MasterFile.LightBusinessObjects.Country Country
        {
            get { return GetProperty(CountryProperty); }
            private set { LoadProperty(CountryProperty, value); }
        }

        public static readonly PropertyInfo<string> PostalCodeProperty = RegisterProperty<string>(c => c.PostalCode);
        public string PostalCode
        {
            get { return GetProperty(PostalCodeProperty); }
            private set { LoadProperty(PostalCodeProperty, value); }
        }

        public static readonly PropertyInfo<string> GPSLongitudeProperty = RegisterProperty<string>(c => c.GPSLongitude);
        public string GPSLongitude
        {
            get { return GetProperty(GPSLongitudeProperty); }
            private set { LoadProperty(GPSLongitudeProperty, value); }
        }

        public static readonly PropertyInfo<string> GPSLattitudeProperty = RegisterProperty<string>(c => c.GPSLattitude);
        public string GPSLattitude
        {
            get { return GetProperty(GPSLattitudeProperty); }
            private set { LoadProperty(GPSLattitudeProperty, value); }
        }

        public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.SalesRepresentative> SalesRepresentativeProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.SalesRepresentative>(c => c.SalesRepresentative);
        public MF_MasterFile.LightBusinessObjects.SalesRepresentative SalesRepresentative
        {
            get { return GetProperty(SalesRepresentativeProperty); }
           private set { LoadProperty(SalesRepresentativeProperty, value); }
        }

        public static readonly PropertyInfo<bool> IsHeadQuarterProperty = RegisterProperty<bool>(c => c.IsHeadQuarter);
        public bool IsHeadQuarter
        {
            get { return GetProperty(IsHeadQuarterProperty); }
            private set { LoadProperty(IsHeadQuarterProperty, value); }
        }

        public static readonly PropertyInfo<bool> IsActiveProperty = RegisterProperty<bool>(c => c.IsActive);
        public bool IsActive
        {
            get { return GetProperty(IsActiveProperty); }
            private set { LoadProperty(IsActiveProperty, value); }
        }

        public static readonly PropertyInfo<byte[]> RowTimestampProperty = RegisterProperty<byte[]>(c => c.RowTimestamp);
        public byte[] RowTimestamp
        {
            get { return GetProperty(RowTimestampProperty); }
            private set { LoadProperty(RowTimestampProperty, value); }
        }

        #endregion

        #region Localized Properties

        public string CityDescription { get { return (IsFr(this.DefaultCollation) ? this.City.DescFr : this.City.DescEn); } }

        #endregion

        #endregion

        #region Search Functions

        #region GetAddress

        [Serializable]
        internal class GetAddressByKeyCriteria : CriteriaBase<GetAddressByKeyCriteria>, Customer._Address.ISearchCriteria
        {
            public long ID { get; set; }
            public string Collation { get; set; }
            public Expression<Func<Models.MF_Customer.Address, bool>> GetWhereExpression()
            {
                return (x => x.ID == this.ID);
            }
            public GetAddressByKeyCriteria(long id, string collation)
            {
                this.ID = id;
                this.Collation = collation;
            }
        }
        public static Customer._Address GetAddress(long id, string collation)
        {
            return DataPortal.Fetch<Customer._Address>(new GetAddressByKeyCriteria(id, collation));
        }
        public static Task<Customer._Address> GetAddressAsync(long id, string collation)
        {
            return DataPortal.FetchAsync<Customer._Address>(new GetAddressByKeyCriteria(id, collation));
        }

        #endregion

        #region GetAddressByCode

        [Serializable]
        internal class GetAddressByCodeCriteria : CriteriaBase<GetAddressByCodeCriteria>, _Address.ISearchCriteria
        {
            public string Code { get; set; }
            public string Collation { get; set; }
            public Expression<Func<Models.MF_Customer.Address, bool>> GetWhereExpression()
            {
                return (x => x.Code == this.Code);
            }
            public GetAddressByCodeCriteria(string code, string collation)
            {
                this.Code = code;
                this.Collation = collation;
            }
        }
        public static Customer._Address GetAddressByCode(string code, string collation)
        {
            return DataPortal.Fetch<Customer._Address>(new GetAddressByCodeCriteria(code, collation));
        }
        public static Task<Customer._Address> GetAddressByCodeAsync(string code, string collation)
        {
            return DataPortal.FetchAsync<Customer._Address>(new GetAddressByCodeCriteria(code, collation));
        }

        #endregion

        #endregion

        #region Model Mappings

        private void FillObjectFromModel(Models.MF_Customer.Address model)
        {
            LoadProperty(IDProperty, model.ID);
            LoadProperty(CodeProperty, model.Code);
            LoadProperty(NameProperty, model.Name);
            LoadProperty(Address1Property, model.Adresse1);
            LoadProperty(Address2Property, model.Adresse2);
            LoadProperty(Address3Property, model.Adresse3);
            LoadProperty(IsHeadQuarterProperty, model.IsHeadQuarter);
            LoadProperty(SalesRepresentativeProperty, MF_MasterFile.LightBusinessObjects.SalesRepresentative.Fetch(model.SalesRepresentativeID, model.SalesRepresentative, this.DefaultCollation));
            LoadProperty(CityProperty, MF_MasterFile.LightBusinessObjects.City.Fetch(model.CityID, model.City, this.DefaultCollation));
            LoadProperty(ProvinceProperty, MF_MasterFile.LightBusinessObjects.Province.Fetch(model.ProvinceID, model.Province, this.DefaultCollation));
            LoadProperty(CountryProperty, MF_MasterFile.LightBusinessObjects.Country.Fetch(model.CountryID, model.Country, this.DefaultCollation));
            LoadProperty(PostalCodeProperty, model.PostalCode);
            LoadProperty(GPSLattitudeProperty, model.GPSCoordinateLatitude);
            LoadProperty(GPSLongitudeProperty, model.GPSCoordinateLongitude);
            LoadProperty(IsActiveProperty, model.IsActive);
            LoadProperty(RowTimestampProperty, model.RowTimestamp);
        }

        #endregion

        #region DataPortal Functions

        internal class DataPortal_FetchArgs
        {
            public string DefaultCollection { get; set; }
            public Models.MF_Customer.Address Model { get; set; }
        }
        internal interface ISearchCriteria
        {
            string Collation { get; set; }
            Expression<Func<Models.MF_Customer.Address, bool>> GetWhereExpression();
        }
        internal static Base.CORE.DataLayer.IDbContextBase DomainDrivenDesignBoundedContext
        {
            get { return new DataLayer.EnterpriseResourcePlanning.CustomerContext(); }
        }

        internal static Customer._Address Fetch(long? id, Models.MF_Customer.Address model, string collation)
        {
            if (id == null) return null;
            if (model != null) return DataPortal.Fetch<Customer._Address>(new DataPortal_FetchArgs() { Model = model, DefaultCollection = collation });
            return DataPortal.Fetch<Customer._Address>(new GetAddressByKeyCriteria((long)id, collation));
        }
        internal static Task<Customer._Address> FetchAsync(long? id, Models.MF_Customer.Address model, string collation)
        {
            if (id == null) return null;
            if (model != null) return DataPortal.FetchAsync<Customer._Address>(new DataPortal_FetchArgs() { Model = model, DefaultCollection = collation });
            return DataPortal.FetchAsync<Customer._Address>(new GetAddressByKeyCriteria((long)id, collation));
        }

        private void DataPortal_Fetch(ISearchCriteria criteria)
        {
            FetchModel(criteria);
        }
        private void Child_Fetch(ISearchCriteria criteria)
        {
            FetchModel(criteria);
        }
        private void FetchModel(ISearchCriteria criteria)
        {
            using (Base.CORE.DataLayer.IDbContextBase _context = DomainDrivenDesignBoundedContext)
            {
                //Selecting + Including
                var query = _context.GetQuery<Models.MF_Customer.Address>();

                // Filtering
                if (criteria.GetWhereExpression() != null)
                    query = query.Where(criteria.GetWhereExpression());

                // Executing
                var model = query.Single();
                if (model != null)
                {
                    // Building
                    DataPortal_FetchArgs args = new DataPortal_FetchArgs() { Model = model, DefaultCollection = criteria.Collation };
                    FetchModel(args);
                }
            }
        }

        private void DataPortal_Fetch(DataPortal_FetchArgs args)
        {
            FetchModel(args);
        }
        private void Child_Fetch(DataPortal_FetchArgs args)
        {
            FetchModel(args);
        }
        private void FetchModel(DataPortal_FetchArgs args)
        {
            this.DefaultCollation = args.DefaultCollection;
            FillObjectFromModel(args.Model);
        }
        #endregion
    }

    #endregion

    #region One-to-Many Relationship Helper -> _Note

    [Serializable]
    public class _NoteCollection : Base.CORE.BusinessObjects.CustomBusinessListBase<_NoteCollection, Customer._Note>
    {
        private _NoteCollection() { /* Require use of factory methods */ }

        public static _NoteCollection FetchChildren(Customer parent)
        {
            return DataPortal.Fetch<Customer._NoteCollection>(parent);
        }
        private void DataPortal_Fetch(Customer parent)
        {
            this.RaiseListChangedEvents = false;
            {
                using (Base.CORE.DataLayer.IDbContextBase _context = Customer.DomainDrivenDesignBoundedContext)
                {
                    //Selecting + Including
                    var query = _context.GetQuery<Models.MF_Customer.CustomerNote>();

                    // Filtering
                    query = query.Where(x => x.CustomerID == parent.ID);

                    // Sorting
                    query = query.OrderBy(x => (x.SortOrder != null ? 0 : 1)).ThenBy(x => x.SortOrder).ThenBy(x => x.CreationDate);

                    // Executing
                    List<Models.MF_Customer.CustomerNote> list = query.ToList();

                    // Building
                    foreach (Models.MF_Customer.CustomerNote model in list)
                        Add(Customer._Note.FetchChild(model.ID, model, parent.DefaultCollation));
                }
            }
            this.RaiseListChangedEvents = true;
        }
    }

    [Serializable]
    public class _Note : Base.CORE.BusinessObjects.CustomBusinessBase<_Note>
    {
        private _Note() : base() { /* Require use of factory methods */ }

        #region Properties

        #region Root Properties

        public static readonly PropertyInfo<long> IDProperty = RegisterProperty<long>(c => c.ID);
        public long ID
        {
            get { return GetProperty(IDProperty); }
            private set { LoadProperty(IDProperty, value); }
        }

        public static readonly PropertyInfo<long> ParentIDProperty = RegisterProperty<long>(c => c.ParentID);
        public long ParentID
        {
            get { return GetProperty(ParentIDProperty); }
            set { SetProperty(ParentIDProperty, value); }
        }

        public static readonly PropertyInfo<string> MemoProperty = RegisterProperty<string>(c => c.Memo);
        public string Memo
        {
            get { return GetProperty(MemoProperty); }
            set { SetProperty(MemoProperty, value); }
        }

        public static readonly PropertyInfo<bool> IsActiveProperty = RegisterProperty<bool>(c => c.IsActive);
        public bool IsActive
        {
            get { return GetProperty(IsActiveProperty); }
            set { SetProperty(IsActiveProperty, value); }
        }

        public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.NoteType> NoteTypeProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.NoteType>(c => c.NoteType);
        public MF_MasterFile.LightBusinessObjects.NoteType NoteType
        {
            get { return GetProperty(NoteTypeProperty); }
            set { SetProperty(NoteTypeProperty, value); }
        }

        public static readonly PropertyInfo<int?> SortOrderProperty = RegisterProperty<int?>(c => c.SortOrder);
        public int? SortOrder
        {
            get { return GetProperty(SortOrderProperty); }
            set { SetProperty(SortOrderProperty, value); }
        }

        public static readonly PropertyInfo<DateTime?> CreationDateProperty = RegisterProperty<DateTime?>(c => c.CreationDate);
        public DateTime? CreationDate
        {
            get { return GetProperty(CreationDateProperty); }
            private set { SetProperty(CreationDateProperty, value); }
        }

        public static readonly PropertyInfo<string> CreationUserProperty = RegisterProperty<string>(c => c.CreationUser);
        public string CreationUser
        {
            get { return GetProperty(CreationUserProperty); }
            private set { SetProperty(CreationUserProperty, value); }
        }

        public static readonly PropertyInfo<DateTime?> LastModificationDateProperty = RegisterProperty<DateTime?>(c => c.LastModificationDate);
        public DateTime? LastModificationDate
        {
            get { return GetProperty(LastModificationDateProperty); }
            private set { SetProperty(LastModificationDateProperty, value); }
        }

        public static readonly PropertyInfo<string> LastModificationUserProperty = RegisterProperty<string>(c => c.LastModificationUser);
        public string LastModificationUser
        {
            get { return GetProperty(LastModificationUserProperty); }
            private set { SetProperty(LastModificationUserProperty, value); }
        }

        public static readonly PropertyInfo<byte[]> RowTimestampProperty = RegisterProperty<byte[]>(c => c.RowTimestamp);
        public byte[] RowTimestamp
        {
            get { return GetProperty(RowTimestampProperty); }
            private set { LoadProperty(RowTimestampProperty, value); }
        }

        #endregion

        #endregion

        #region Search Functions

        #region GetNote

        [Serializable]
        internal class GetNoteByKeyCriteria : CriteriaBase<GetNoteByKeyCriteria>, Customer._Note.ISearchCriteria
        {
            public long ID { get; set; }
            public string Collation { get; set; }
            public Expression<Func<Models.MF_Customer.CustomerNote, bool>> GetWhereExpression()
            {
                return (x => x.ID == this.ID);
            }
            public GetNoteByKeyCriteria(long id, string collation)
            {
                this.ID = id;
                this.Collation = collation;
            }
        }
        public static Customer._Note GetNote(long id, string collation)
        {
            return DataPortal.Fetch<Customer._Note>(new GetNoteByKeyCriteria(id, collation));
        }
        public static Task<Customer._Note> GetNoteAsync(long id, string collation)
        {
            return DataPortal.FetchAsync<Customer._Note>(new GetNoteByKeyCriteria(id, collation));
        }

        #endregion

        #region GetSpecificNote

        [Serializable]
        internal class GetSpecificNoteCriteria : CriteriaBase<GetSpecificNoteCriteria>, Customer._Note.ISearchCriteria
        {
            public long ID { get; set; }
            public byte[] RowTimestamp { get; set; }
            public string Collation { get; set; }
            public Expression<Func<Models.MF_Customer.CustomerNote, bool>> GetWhereExpression()
            {
                return (x => x.ID == this.ID);
            }
            public GetSpecificNoteCriteria(long id, byte[] RowTimestamp, string collation)
            {
                this.ID = id;
                this.RowTimestamp = RowTimestamp;
                this.Collation = collation;
            }
        }
        public static Customer._Note GetSpecificNote(long id, byte[] RowTimestamp, string collation)
        {
            return DataPortal.Fetch<Customer._Note>(new GetSpecificNoteCriteria(id, RowTimestamp, collation));
        }
        public static Task<Customer._Note> GetSpecificNoteAsync(long id, byte[] RowTimestamp, string collation)
        {
            return DataPortal.FetchAsync<Customer._Note>(new GetSpecificNoteCriteria(id, RowTimestamp, collation));
        }

        #endregion

        #endregion

        #region Model Mappings

        private void FillObjectFromModel(Models.MF_Customer.CustomerNote model)
        {
            using (BypassPropertyChecks)
            {
                LoadProperty(IDProperty, model.ID);
                LoadProperty(ParentIDProperty, model.CustomerID);
                LoadProperty(MemoProperty, model.Text);
                LoadProperty(NoteTypeProperty, MF_MasterFile.LightBusinessObjects.NoteType.Fetch(model.NoteTypeID, model.NoteType, this.DefaultCollation));
                LoadProperty(IsActiveProperty, model.IsActive);
                LoadProperty(SortOrderProperty, model.SortOrder);
                LoadProperty(CreationDateProperty, model.CreationDate);
                LoadProperty(CreationUserProperty, model.CreationUser);
                LoadProperty(LastModificationDateProperty, model.LastModificationDate);
                LoadProperty(LastModificationUserProperty, model.LastModificationUser);
                LoadProperty(RowTimestampProperty, model.RowTimestamp);
            }
        }
        private void FillModelFromObject(Models.MF_Customer.CustomerNote model)
        {
            if (this.IsChild && this.Parent is Customer._NoteCollection && this.Parent.Parent is Customer)
                model.CustomerID = ((Customer)this.Parent.Parent).ID;
            else
                model.CustomerID = this.ParentID;

            model.NoteTypeID = this.NoteType.ID;
            model.Text = this.Memo;
            model.IsActive = this.IsActive;
            model.SortOrder = this.SortOrder;
            model.CreationDate = null;
            model.CreationUser = null;
            model.LastModificationDate = null;
            model.LastModificationUser = null;
        }

        #endregion

        #region DataPortal Functions

        internal class DataPortal_FetchArgs
        {
            public string DefaultCollection { get; set; }
            public Models.MF_Customer.CustomerNote Model { get; set; }
        }
        internal interface ISearchCriteria
        {
            string Collation { get; set; }
            Expression<Func<Models.MF_Customer.CustomerNote, bool>> GetWhereExpression();
        }
        internal static Base.CORE.DataLayer.IDbContextBase DomainDrivenDesignBoundedContext
        {
            get { return new DataLayer.EnterpriseResourcePlanning.CustomerContext(); }
        }

        internal static Customer._Note FetchChild(long? id, Models.MF_Customer.CustomerNote model, string collation)
        {
            if (id == null) return null;
            if (model != null) return DataPortal.FetchChild<Customer._Note>(new DataPortal_FetchArgs() { Model = model, DefaultCollection = collation });
            return DataPortal.FetchChild<Customer._Note>(new GetNoteByKeyCriteria((long)id, collation));
        }

        protected override void DataPortal_Create()
        {
            CreateObject();
        }
        protected override void Child_Create()
        {
            base.Child_Create();
            CreateObject();
        }
        private void CreateObject()
        {
            this.IsActive = true;
            this.CreationDate = System.DateTime.Now;
            this.CreationUser = Csla.ApplicationContext.User.Identity.Name;
        }

        private void DataPortal_Fetch(ISearchCriteria criteria)
        {
            FetchModel(criteria);
        }
        private void Child_Fetch(ISearchCriteria criteria)
        {
            FetchModel(criteria);
        }
        private void FetchModel(ISearchCriteria criteria)
        {
            using (Base.CORE.DataLayer.IDbContextBase _context = DomainDrivenDesignBoundedContext)
            {
                //Selecting + Including
                var query = _context.GetQuery<Models.MF_Customer.CustomerNote>();

                // Filtering
                if (criteria.GetWhereExpression() != null)
                    query = query.Where(criteria.GetWhereExpression());

                // Executing
                var model = query.Single();
                if (model != null)
                {
                    // Building
                    DataPortal_FetchArgs args = new DataPortal_FetchArgs() { Model = model, DefaultCollection = criteria.Collation };
                    FetchModel(args);
                }
            }
        }

        private void DataPortal_Fetch(DataPortal_FetchArgs args)
        {
            FetchModel(args);
        }
        private void Child_Fetch(DataPortal_FetchArgs args)
        {
            FetchModel(args);
        }
        private void FetchModel(DataPortal_FetchArgs args)
        {
            this.DefaultCollation = args.DefaultCollection;
            FillObjectFromModel(args.Model);
        }

        protected override void DataPortal_Insert() { InsertModel(); }
        private void Child_Insert() { InsertModel(); }
        private void InsertModel()
        {
            using (Base.CORE.DataLayer.IDbContextBase _context = DomainDrivenDesignBoundedContext)
            {
                /*
                var query = from o in _context.GetQuery<Models.ClientNote>()
                            where o.Code == this.Code
                            select o;
                if (query.Count() > 0)
                    throw new DataPortalException("Code already exists", this);
                */

                Models.MF_Customer.CustomerNote model = new Models.MF_Customer.CustomerNote();
                FillModelFromObject(model);

                _context.Add<Models.MF_Customer.CustomerNote>(model);
                _context.SaveChanges();

                FetchModel(new GetNoteByKeyCriteria(model.ID, this.DefaultCollation));
            }
        }

        protected override void DataPortal_Update() { UpdateModel(); }
        private void Child_Update() { UpdateModel(); }
        private void UpdateModel()
        {
            using (Base.CORE.DataLayer.IDbContextBase _context = DomainDrivenDesignBoundedContext)
            {
                var query = from o in _context.GetQuery<Models.MF_Customer.CustomerNote>()
                            where o.ID == this.ID
                            where o.RowTimestamp == this.RowTimestamp
                            select o;

                var model = query.SingleOrDefault();
                if (model == null)
                    throw new DataPortalException("ConcurrencyCheck Failed", this);

                FillModelFromObject(model);

                _context.Update<Models.MF_Customer.CustomerNote>(model);
                _context.SaveChanges();

                FetchModel(new GetNoteByKeyCriteria(model.ID, this.DefaultCollation));
            }
        }

        protected override void DataPortal_DeleteSelf() { DeleteModel(); }
        private void Child_DeleteSelf() { DeleteModel(); }
        private void DeleteModel()
        {
            using (Base.CORE.DataLayer.IDbContextBase _context = DomainDrivenDesignBoundedContext)
            {
                var query = from o in _context.GetQuery<Models.MF_Customer.CustomerNote>()
                            where o.ID == this.ID
                            where o.RowTimestamp == this.RowTimestamp
                            select o;

                var model = query.SingleOrDefault();
                if (model == null)
                    throw new DataPortalException("ConcurrencyCheck Failed", this);

                _context.Delete<Models.MF_Customer.CustomerNote>(model);
                _context.SaveChanges();

            }
        }

        #endregion

        #region Validation

        protected override void AddBusinessRules()
        {
            base.AddBusinessRules();

            //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(MemoProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.CustomerNote_MemoProperty_RequiredRule; }*/ });

            //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(SortOrderProperty, 16) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.CustomerNote_SortOrderProperty_MaxLengthRule, 16); }*/ });
        }

        #endregion

    }

    #endregion

    #region One-to-Many Relationship Helper -> _Contact

    [Serializable]
    public class _ContactCollection : Base.CORE.BusinessObjects.CustomBusinessListBase<_ContactCollection, Customer._Contact>
    {
        private _ContactCollection() { /* Require use of factory methods */ }

        public static _ContactCollection FetchChildren(Customer parent)
        {
            return DataPortal.Fetch<Customer._ContactCollection>(parent);
        }
        private void DataPortal_Fetch(Customer parent)
        {
            this.RaiseListChangedEvents = false;
            {
                using (Base.CORE.DataLayer.IDbContextBase context = Customer.DomainDrivenDesignBoundedContext)
                {
                    //Selecting + Including
                    var query = context.GetQuery<Models.MF_Customer.Contact>();

                    // Filtering
                    query = query.Where(x => x.CustomerID == parent.ID);

                    // Sorting
                    query = query.OrderBy(x => x.CreationDate);

                    // Executing
                    List<Models.MF_Customer.Contact> list = query.ToList();

                    // Building
                    foreach (Models.MF_Customer.Contact model in list)
                        Add(Customer._Contact.FetchChild(model.ID, model, parent.DefaultCollation));
                }
            }
            this.RaiseListChangedEvents = true;
        }
    }

    [Serializable]
    public class _Contact : Base.CORE.BusinessObjects.CustomBusinessBase<_Contact>
    {
        private _Contact() : base() { /* Require use of factory methods */ }

        #region Properties

        #region Root Properties

        public static readonly PropertyInfo<long> IDProperty = RegisterProperty<long>(c => c.ID);
        public long ID
        {
            get { return GetProperty(IDProperty); }
            private set { LoadProperty(IDProperty, value); }
        }

        public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(c => c.Name);
        public string Name
        {
            get { return GetProperty(NameProperty); }
            set { SetProperty(NameProperty, value); }
        }

        public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.ContactType> ContactTypeProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.ContactType>(c => c.ContactType);
        public MF_MasterFile.LightBusinessObjects.ContactType ContactType
        {
            get { return GetProperty(ContactTypeProperty); }
            set { SetProperty(ContactTypeProperty, value); }
        }

        public static readonly PropertyInfo<string> Tel1Property = RegisterProperty<string>(c => c.Tel1);
        public string Tel1
        {
            get { return GetProperty(Tel1Property); }
            set { SetProperty(Tel1Property, value); }
        }

        public static readonly PropertyInfo<string> Tel1LongDistanceCodeProperty = RegisterProperty<string>(c => c.Tel1LongDistanceCode);
        public string Tel1LongDistanceCode
        {
            get { return GetProperty(Tel1LongDistanceCodeProperty); }
            set { SetProperty(Tel1LongDistanceCodeProperty, value); }
        }

        public static readonly PropertyInfo<string> Ext1Property = RegisterProperty<string>(c => c.Ext1);
        public string Ext1
        {
            get { return GetProperty(Ext1Property); }
            set { SetProperty(Ext1Property, value); }
        }

        public static readonly PropertyInfo<string> Tel2Property = RegisterProperty<string>(c => c.Tel2);
        public string Tel2
        {
            get { return GetProperty(Tel2Property); }
            set { SetProperty(Tel2Property, value); }
        }

        public static readonly PropertyInfo<string> Tel2LongDistanceCodeProperty = RegisterProperty<string>(c => c.Tel2LongDistanceCode);
        public string Tel2LongDistanceCode
        {
            get { return GetProperty(Tel2LongDistanceCodeProperty); }
            set { SetProperty(Tel2LongDistanceCodeProperty, value); }
        }

        public static readonly PropertyInfo<string> Ext2Property = RegisterProperty<string>(c => c.Ext2);
        public string Ext2
        {
            get { return GetProperty(Ext2Property); }
            set { SetProperty(Ext2Property, value); }
        }

        public static readonly PropertyInfo<string> EmailProperty = RegisterProperty<string>(c => c.Email);
        public string Email
        {
            get { return GetProperty(EmailProperty); }
            set { SetProperty(EmailProperty, value); }
        }

        public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.Language> LangageProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.Language>(c => c.Langage);
        public MF_MasterFile.LightBusinessObjects.Language Langage
        {
            get { return GetProperty(LangageProperty); }
            set { SetProperty(LangageProperty, value); }
        }

        public static readonly PropertyInfo<bool> IsActiveProperty = RegisterProperty<bool>(c => c.IsActive);
        public bool IsActive
        {
            get { return GetProperty(IsActiveProperty); }
            set { SetProperty(IsActiveProperty, value); }
        }

        public static readonly PropertyInfo<int?> SortOrderProperty = RegisterProperty<int?>(c => c.SortOrder);
        public int? SortOrder
        {
            get { return GetProperty(SortOrderProperty); }
            set { SetProperty(SortOrderProperty, value); }
        }
        public static readonly PropertyInfo<DateTime?> CreationDateProperty = RegisterProperty<DateTime?>(c => c.CreationDate);
        public DateTime? CreationDate
        {
            get { return GetProperty(CreationDateProperty); }
            set { SetProperty(CreationDateProperty, value); }
        }

        public static readonly PropertyInfo<string> CreationUserProperty = RegisterProperty<string>(c => c.CreationUser);
        public string CreationUser
        {
            get { return GetProperty(CreationUserProperty); }
            set { SetProperty(CreationUserProperty, value); }
        }

        public static readonly PropertyInfo<DateTime?> LastModificationDateProperty = RegisterProperty<DateTime?>(c => c.LastModificationDate);
        public DateTime? LastModificationDate
        {
            get { return GetProperty(LastModificationDateProperty); }
            set { SetProperty(LastModificationDateProperty, value); }
        }

        public static readonly PropertyInfo<string> LastModificationUserProperty = RegisterProperty<string>(c => c.LastModificationUser);
        public string LastModificationUser
        {
            get { return GetProperty(LastModificationUserProperty); }
            set { SetProperty(LastModificationUserProperty, value); }
        }

        public static readonly PropertyInfo<byte[]> RowTimestampProperty = RegisterProperty<byte[]>(c => c.RowTimestamp);
        public byte[] RowTimestamp
        {
            get { return GetProperty(RowTimestampProperty); }
            private set { LoadProperty(RowTimestampProperty, value); }
        }
        #endregion

        #endregion

        #region Model Mappings

        private void FillObjectFromModel(Models.MF_Customer.Contact model)
        {
            LoadProperty(IDProperty, model.ID);
            LoadProperty(NameProperty, model.Name);
            LoadProperty(ContactTypeProperty, MF_MasterFile.LightBusinessObjects.ContactType.Fetch(model.ContactTypeID, model.ContactType, this.DefaultCollation));
            LoadProperty(Tel1Property, model.Tel1);
            LoadProperty(Tel1LongDistanceCodeProperty, model.Tel1LongDistanceCode);
            LoadProperty(Ext1Property, model.Ext1);
            LoadProperty(Tel2Property, model.Tel2);
            LoadProperty(Tel2LongDistanceCodeProperty, model.Tel2LongDistanceCode);
            LoadProperty(Ext2Property, model.Ext2);
            LoadProperty(EmailProperty, model.Email);
            LoadProperty(LangageProperty, MF_MasterFile.LightBusinessObjects.Language.Fetch(model.LangageID, model.Language, this.DefaultCollation));
            LoadProperty(IsActiveProperty, model.IsActive);
            LoadProperty(SortOrderProperty, model.SortOrder);
            LoadProperty(CreationDateProperty, model.CreationDate);
            LoadProperty(CreationUserProperty, model.CreationUser);
            LoadProperty(LastModificationDateProperty, model.LastModificationDate);
            LoadProperty(LastModificationUserProperty, model.LastModificationUser);
            LoadProperty(RowTimestampProperty, model.RowTimestamp);
        }

        private void FillModelFromObject(Models.MF_Customer.Contact model)
        {
            model.CustomerID = ((Customer)this.Parent.Parent).ID;
            model.Name = this.Name;
            model.ContactTypeID = this.ContactType.ID;
            model.Tel1 = this.Tel1;
            model.Tel1LongDistanceCode = this.Tel1LongDistanceCode;
            model.Ext1 = this.Ext1;
            model.Tel2 = this.Tel2;
            model.Tel2LongDistanceCode = this.Tel2LongDistanceCode;
            model.Ext2 = this.Ext2;
            model.Email = this.Email;
            model.LangageID = this.Langage.ID;
            model.IsActive = this.IsActive;
            model.SortOrder = this.SortOrder;
            model.CreationDate = null;
            model.CreationUser = null;
            model.LastModificationDate = null;
            model.LastModificationUser = null;
        }

        #endregion

        #region DataPortal Functions

        internal class DataPortal_FetchArgs
        {
            public string DefaultCollection { get; set; }
            public Models.MF_Customer.Contact Model { get; set; }
        }

        internal static Customer._Contact FetchChild(long? id, Models.MF_Customer.Contact model, string collation)
        {
            if (id == null) return null;
            if (model != null) return DataPortal.FetchChild<Customer._Contact>(new DataPortal_FetchArgs() { Model = model, DefaultCollection = collation });
            return null;
        }

        protected override void Child_Create()
        {
            base.Child_Create();
            CreateObject();
        }

        private void CreateObject()
        {
            this.CreationDate = System.DateTime.Now;
            this.CreationUser = Csla.ApplicationContext.User.Identity.Name;
        }

        private void Child_Fetch(DataPortal_FetchArgs args)
        {
            FetchModel(args);
        }
        private void FetchModel(DataPortal_FetchArgs args)
        {
            this.DefaultCollation = args.DefaultCollection;
            FillObjectFromModel(args.Model);
        }

        private void Child_Insert(Base.CORE.DataLayer.IDbContextBase context, Models.MF_Customer.Customer parentModel) { InsertModel(context, parentModel); }
        private void InsertModel(Base.CORE.DataLayer.IDbContextBase context, Models.MF_Customer.Customer parentModel)
        {
            Models.MF_Customer.Contact model = new Models.MF_Customer.Contact();
            FillModelFromObject(model);
            model.Customer = parentModel;
            context.Add<Models.MF_Customer.Contact>(model);
        }

        private void Child_Update(Base.CORE.DataLayer.IDbContextBase context, Models.MF_Customer.Customer parentModel) { UpdateModel(context, parentModel); }
        private void UpdateModel(Base.CORE.DataLayer.IDbContextBase context, Models.MF_Customer.Customer parentModel)
        {
            var query = context.GetQuery<Models.MF_Customer.Contact>().Where(x => x.ID == this.ID && x.RowTimestamp == this.RowTimestamp);
            var model = query.SingleOrDefault();
            if (model == null)
                throw new DataPortalException("ConcurrencyCheck Failed", this);

            FillModelFromObject(model);
            context.Update<Models.MF_Customer.Contact>(model);
        }

        private void Child_DeleteSelf(Base.CORE.DataLayer.IDbContextBase context, Models.MF_Customer.Customer parentModel) { DeleteModel(context, parentModel); }
        private void DeleteModel(Base.CORE.DataLayer.IDbContextBase context, Models.MF_Customer.Customer parentModel)
        {
            var query = context.GetQuery<Models.MF_Customer.Contact>().Where(x => x.ID == this.ID && x.RowTimestamp == this.RowTimestamp);
            var model = query.SingleOrDefault();
            if (model == null)
                throw new DataPortalException("ConcurrencyCheck Failed", this);

            context.Delete<Models.MF_Customer.Contact>(model);
        }

        #endregion

    }

    //[Serializable]
    //public class _ContactCollection : Base.CORE.BusinessObjects.CustomReadOnlyListBase<_ContactCollection, Customer._Contact>
    //{
    //    private _ContactCollection() { /* Require use of factory methods */ }

    //    public static _ContactCollection FetchChildren(Customer parent)
    //    {
    //        return DataPortal.Fetch<Customer._ContactCollection>(parent);
    //    }
    //    private void DataPortal_Fetch(Customer parent)
    //    {
    //        this.RaiseListChangedEvents = false;
    //        {
    //            using (Base.CORE.DataLayer.IDbContextBase _context = Customer.DomainDrivenDesignBoundedContext)
    //            {
    //                //Selecting + Including
    //                var query = _context.GetQuery<Models.MF_Customer.Contact>();

    //                // Filtering
    //                query = query.Where(x => x.CustomerID == parent.ID);

    //                // Sorting
    //                query = query.OrderBy(x => (x.SortOrder != null ? 0 : 1)).ThenBy(x => x.SortOrder).ThenBy(x => x.CreationDate);

    //                // Executing
    //                List<Models.MF_Customer.Contact> list = query.ToList();

    //                // Building
    //                foreach (Models.MF_Customer.Contact model in list)
    //                    Add(Customer._Contact.GetContact(model.ID, parent.DefaultCollation));
    //            }
    //        }
    //        this.RaiseListChangedEvents = true;
    //    }
    //}

    //[Serializable]
    //public class _Contact : Base.CORE.BusinessObjects.CustomReadOnlyBase<_Contact>
    //{
    //    private _Contact() : base() { /* Require use of factory methods */ }

    //    #region Properties

    //    #region Root Properties

    //    public static readonly PropertyInfo<long> IDProperty = RegisterProperty<long>(c => c.ID);
    //    public long ID
    //    {
    //        get { return GetProperty(IDProperty); }
    //        private set { LoadProperty(IDProperty, value); }
    //    }

    //    public static readonly PropertyInfo<long> ParentIDProperty = RegisterProperty<long>(c => c.ParentID);
    //    public long ParentID
    //    {
    //        get { return GetProperty(ParentIDProperty); }
    //        private set { LoadProperty(ParentIDProperty, value); }
    //    }

    //    public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.ContactType> ContactTypeProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.ContactType>(c => c.ContactType);
    //    public MF_MasterFile.LightBusinessObjects.ContactType ContactType
    //    {
    //        get { return GetProperty(ContactTypeProperty); }
    //        private set { LoadProperty(ContactTypeProperty, value); }
    //    }

    //    public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(c => c.Name);
    //    public string Name
    //    {
    //        get { return GetProperty(NameProperty); }
    //        private set { LoadProperty(NameProperty, value); }
    //    }

    //    public static readonly PropertyInfo<string> Tel1Property = RegisterProperty<string>(c => c.Tel1);
    //    public string Tel1
    //    {
    //        get { return GetProperty(Tel1Property); }
    //        private set { LoadProperty(Tel1Property, value); }
    //    }

    //    public static readonly PropertyInfo<string> Tel1LongDistanceCodeProperty = RegisterProperty<string>(c => c.Tel1LongDistanceCode);
    //    public string Tel1LongDistanceCode
    //    {
    //        get { return GetProperty(Tel1LongDistanceCodeProperty); }
    //        private set { LoadProperty(Tel1LongDistanceCodeProperty, value); }
    //    }

    //    public static readonly PropertyInfo<string> Ext1Property = RegisterProperty<string>(c => c.Ext1);
    //    public string Ext1
    //    {
    //        get { return GetProperty(Ext1Property); }
    //        private set { LoadProperty(Ext1Property, value); }
    //    }

    //    public static readonly PropertyInfo<string> FaxProperty = RegisterProperty<string>(c => c.Fax);
    //    public string Fax
    //    {
    //        get { return GetProperty(FaxProperty); }
    //        private set { LoadProperty(FaxProperty, value); }
    //    }

    //    public static readonly PropertyInfo<string> FaxLongDistanceCodeProperty = RegisterProperty<string>(c => c.FaxLongDistanceCode);
    //    public string FaxLongDistanceCode
    //    {
    //        get { return GetProperty(FaxLongDistanceCodeProperty); }
    //        private set { LoadProperty(FaxLongDistanceCodeProperty, value); }
    //    }

    //    public static readonly PropertyInfo<string> EmailProperty = RegisterProperty<string>(c => c.Email);
    //    public string Email
    //    {
    //        get { return GetProperty(EmailProperty); }
    //        private set { LoadProperty(EmailProperty, value); }
    //    }

    //    public static readonly PropertyInfo<MF_MasterFile.LightBusinessObjects.Language> LanguageProperty = RegisterProperty<MF_MasterFile.LightBusinessObjects.Language>(c => c.Language);
    //    public MF_MasterFile.LightBusinessObjects.Language Language
    //    {
    //        get { return GetProperty(LanguageProperty); }
    //        private set { LoadProperty(LanguageProperty, value); }
    //    }

    //    public static readonly PropertyInfo<bool> IsActiveProperty = RegisterProperty<bool>(c => c.IsActive);
    //    public bool IsActive
    //    {
    //        get { return GetProperty(IsActiveProperty); }
    //        private set { LoadProperty(IsActiveProperty, value); }
    //    }

    //    public static readonly PropertyInfo<int?> SortOrderProperty = RegisterProperty<int?>(c => c.SortOrder);
    //    public int? SortOrder
    //    {
    //        get { return GetProperty(SortOrderProperty); }
    //        private set { LoadProperty(SortOrderProperty, value); }
    //    }

    //    public static readonly PropertyInfo<DateTime?> CreationDateProperty = RegisterProperty<DateTime?>(c => c.CreationDate);
    //    public DateTime? CreationDate
    //    {
    //        get { return GetProperty(CreationDateProperty); }
    //        private set { LoadProperty(CreationDateProperty, value); }
    //    }

    //    public static readonly PropertyInfo<string> CreationUserProperty = RegisterProperty<string>(c => c.CreationUser);
    //    public string CreationUser
    //    {
    //        get { return GetProperty(CreationUserProperty); }
    //        private set { LoadProperty(CreationUserProperty, value); }
    //    }

    //    public static readonly PropertyInfo<DateTime?> LastModificationDateProperty = RegisterProperty<DateTime?>(c => c.LastModificationDate);
    //    public DateTime? LastModificationDate
    //    {
    //        get { return GetProperty(LastModificationDateProperty); }
    //        private set { LoadProperty(LastModificationDateProperty, value); }
    //    }

    //    public static readonly PropertyInfo<string> LastModificationUserProperty = RegisterProperty<string>(c => c.LastModificationUser);
    //    public string LastModificationUser
    //    {
    //        get { return GetProperty(LastModificationUserProperty); }
    //        private set { LoadProperty(LastModificationUserProperty, value); }
    //    }

    //    public static readonly PropertyInfo<byte[]> RowTimestampProperty = RegisterProperty<byte[]>(c => c.RowTimestamp);
    //    public byte[] RowTimestamp
    //    {
    //        get { return GetProperty(RowTimestampProperty); }
    //        private set { LoadProperty(RowTimestampProperty, value); }
    //    }

    //    #endregion

    //    #endregion

    //    #region Search Functions

    //    #region GetContact

    //    [Serializable]
    //    internal class GetContactByKeyCriteria : CriteriaBase<GetContactByKeyCriteria>, Customer._Contact.ISearchCriteria
    //    {
    //        public long ID { get; set; }
    //        public string Collation { get; set; }
    //        public Expression<Func<Models.MF_Customer.Contact, bool>> GetWhereExpression()
    //        {
    //            return (x => x.ID == this.ID);
    //        }
    //        public GetContactByKeyCriteria(long id, string collation)
    //        {
    //            this.ID = id;
    //            this.Collation = collation;
    //        }
    //    }
    //    public static Customer._Contact GetContact(long id, string collation)
    //    {
    //        return DataPortal.Fetch<Customer._Contact>(new GetContactByKeyCriteria(id, collation));
    //    }
    //    public static Task<Customer._Contact> GetContactAsync(long id, string collation)
    //    {
    //        return DataPortal.FetchAsync<Customer._Contact>(new GetContactByKeyCriteria(id, collation));
    //    }

    //    #endregion

    //    #region GetSpecificContact

    //    [Serializable]
    //    internal class GetSpecificContactCriteria : CriteriaBase<GetSpecificContactCriteria>, Customer._Contact.ISearchCriteria
    //    {
    //        public long ID { get; set; }
    //        public byte[] RowTimestamp { get; set; }
    //        public string Collation { get; set; }
    //        public Expression<Func<Models.MF_Customer.Contact, bool>> GetWhereExpression()
    //        {
    //            return (x => x.ID == this.ID);
    //        }
    //        public GetSpecificContactCriteria(long id, byte[] RowTimestamp, string collation)
    //        {
    //            this.ID = id;
    //            this.RowTimestamp = RowTimestamp;
    //            this.Collation = collation;
    //        }
    //    }
    //    public static Customer._Contact GetSpecificContact(long id, byte[] RowTimestamp, string collation)
    //    {
    //        return DataPortal.Fetch<Customer._Contact>(new GetSpecificContactCriteria(id, RowTimestamp, collation));
    //    }
    //    public static Task<Customer._Contact> GetSpecificContactAsync(long id, byte[] RowTimestamp, string collation)
    //    {
    //        return DataPortal.FetchAsync<Customer._Contact>(new GetSpecificContactCriteria(id, RowTimestamp, collation));
    //    }

    //    #endregion

    //    #endregion

    //    #region Model Mappings

    //    private void FillObjectFromModel(Models.MF_Customer.Contact model)
    //    {
    //        LoadProperty(IDProperty, model.ID);
    //        LoadProperty(ParentIDProperty, model.CustomerID);
    //        LoadProperty(ContactTypeProperty, MF_MasterFile.LightBusinessObjects.ContactType.Fetch(model.ContactTypeID, model.ContactType, this.DefaultCollation));
    //        LoadProperty(NameProperty, model.Name);
    //        LoadProperty(Tel1Property, model.Tel1);
    //        LoadProperty(Tel1LongDistanceCodeProperty, model.Tel1LongDistanceCode);
    //        LoadProperty(Ext1Property, model.Ext1);
    //        LoadProperty(FaxProperty, model.Fax);
    //        LoadProperty(FaxLongDistanceCodeProperty, model.FaxLongDistanceCode);
    //        LoadProperty(EmailProperty, model.Email);
    //        LoadProperty(LanguageProperty, MF_MasterFile.LightBusinessObjects.Language.Fetch(model.LangageID, model.Language, this.DefaultCollation));
    //        LoadProperty(IsActiveProperty, model.IsActive);
    //        LoadProperty(SortOrderProperty, model.SortOrder);
    //        LoadProperty(CreationDateProperty, model.CreationDate);
    //        LoadProperty(CreationUserProperty, model.CreationUser);
    //        LoadProperty(LastModificationDateProperty, model.LastModificationDate);
    //        LoadProperty(LastModificationUserProperty, model.LastModificationUser);
    //        LoadProperty(RowTimestampProperty, model.RowTimestamp);
    //    }

    //    #endregion

    //    #region DataPortal Functions

    //    internal class DataPortal_FetchArgs
    //    {
    //        public string DefaultCollection { get; set; }
    //        public Models.MF_Customer.Contact Model { get; set; }
    //    }
    //    internal interface ISearchCriteria
    //    {
    //        string Collation { get; set; }
    //        Expression<Func<Models.MF_Customer.Contact, bool>> GetWhereExpression();
    //    }
    //    internal static Base.CORE.DataLayer.IDbContextBase DomainDrivenDesignBoundedContext
    //    {
    //        get { return new DataLayer.EnterpriseResourcePlanning.CustomerContext(); }
    //    }

    //    internal static Customer._Contact FetchChild(long? id, Models.MF_Customer.Contact model, string collation)
    //    {
    //        if (id == null) return null;
    //        if (model != null) return DataPortal.FetchChild<Customer._Contact>(new DataPortal_FetchArgs() { Model = model, DefaultCollection = collation });
    //        return DataPortal.FetchChild<Customer._Contact>(new GetContactByKeyCriteria((long)id, collation));
    //    }

    //    private void DataPortal_Fetch(ISearchCriteria criteria)
    //    {
    //        FetchModel(criteria);
    //    }
    //    private void Child_Fetch(ISearchCriteria criteria)
    //    {
    //        FetchModel(criteria);
    //    }
    //    private void FetchModel(ISearchCriteria criteria)
    //    {
    //        using (Base.CORE.DataLayer.IDbContextBase _context = DomainDrivenDesignBoundedContext)
    //        {
    //            //Selecting + Including
    //            var query = _context.GetQuery<Models.MF_Customer.Contact>();

    //            // Filtering
    //            if (criteria.GetWhereExpression() != null)
    //                query = query.Where(criteria.GetWhereExpression());

    //            // Executing
    //            var model = query.Single();
    //            if (model != null)
    //            {
    //                // Building
    //                DataPortal_FetchArgs args = new DataPortal_FetchArgs() { Model = model, DefaultCollection = criteria.Collation };
    //                FetchModel(args);
    //            }
    //        }
    //    }

    //    private void DataPortal_Fetch(DataPortal_FetchArgs args)
    //    {
    //        FetchModel(args);
    //    }
    //    private void Child_Fetch(DataPortal_FetchArgs args)
    //    {
    //        FetchModel(args);
    //    }
    //    private void FetchModel(DataPortal_FetchArgs args)
    //    {
    //        this.DefaultCollation = args.DefaultCollection;
    //        FillObjectFromModel(args.Model);
    //    }

    //    #endregion

    //    #region Validation

    //    protected override void AddBusinessRules()
    //    {
    //        base.AddBusinessRules();

    //        // BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(ContactTypeProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.CustomerContact_ContactTypeProperty_RequiredRule; }*/ });
    //        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(NameProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.CustomerContact_NameProperty_RequiredRule; }*/ });
    //        //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(LanguageProperty) { Priority = 0/*, MessageDelegate = () => { return Resources.CustomerContact_LanguageProperty_RequiredRule; }*/ });

    //        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(NameProperty, 128) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.CustomerContact_NameProperty_MaxLengthRule, 128); }*/ });
    //        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(FunctionProperty, 32) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.CustomerContact_FunctionProperty_MaxLengthRule, 32); }*/ });
    //        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(Address1Property, 64) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.CustomerContact_Address1Property_MaxLengthRule, 64); }*/ });
    //        // BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(Address2Property, 64) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.CustomerContact_Address2Property_MaxLengthRule, 64); }*/ });
    //        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(Address3Property, 64) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.CustomerContact_Address3Property_MaxLengthRule, 64); }*/ });
    //        // BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(PostalCodeProperty, 16) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.CustomerContact_Address3Property_MaxLengthRule, 64); }*/ });
    //        //BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(PhoneNumber1Property, 32) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.CustomerContact_PhoneNumber1Property_MaxLengthRule, 32); }*/ });
    //        // BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(PhoneNumber2Property, 32) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.CustomerContact_PhoneNumber2Property_MaxLengthRule, 32); }*/ });
    //        // BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(FaxNumberProperty, 32) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.CustomerContact_FaxNumberProperty_MaxLengthRule, 32); }*/ });
    //        // BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(EmailAddressProperty, 256) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.CustomerContact_EmailAddressProperty_MaxLengthRule, 256); }*/ });
    //        // BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(SortOrderProperty, 128) { Priority = 1/*, MessageDelegate = () => { return string.Format(Resources.CustomerContact_SortOrderProperty_MaxLengthRule, 128); }*/ });
    //    }

    //    #endregion

    //    #region One-to-Many Relationship Helper -> _VolumeDiscount

    //    //[Serializable]
    //    //public class _VolumeDiscountCollection : Base.CORE.BusinessObjects.CustomBusinessListBase<_VolumeDiscountCollection, Customer._VolumeDiscount>
    //    //{
    //    //    private _VolumeDiscountCollection() { /* Require use of factory methods */ }

    //    //    public static _VolumeDiscountCollection FetchChildren(Customer parent)
    //    //    {
    //    //        return DataPortal.Fetch<Customer._VolumeDiscountCollection>(parent);
    //    //    }
    //    //    private void DataPortal_Fetch(Customer parent)
    //    //    {
    //    //        this.RaiseListChangedEvents = false;
    //    //        {
    //    //            using (Base.CORE.DataLayer.IDbContextBase _context = Customer.DomainDrivenDesignBoundedContext)
    //    //            {
    //    //                //Selecting + Including
    //    //                var query = _context.GetQuery<Models.ClientRabaisVolume>();

    //    //                // Filtering
    //    //                query = query.Where(x => x.ClientID == parent.ID);

    //    //                // Executing
    //    //                List<Models.ClientRabaisVolume> list = query.ToList();

    //    //                // Building
    //    //                foreach (Models.ClientRabaisVolume model in list)
    //    //                    Add(Customer._VolumeDiscount.FetchChild(model.ClientRabaisVolumeID, model, parent.DefaultCollation));
    //    //            }
    //    //        }
    //    //        this.RaiseListChangedEvents = true;
    //    //    }
    //    //}

    //    //[Serializable]
    //    //public class _VolumeDiscount : Base.CORE.BusinessObjects.CustomBusinessBase<_VolumeDiscount>
    //    //{
    //    //    private _VolumeDiscount() : base() { /* Require use of factory methods */ }

    //    //    #region Properties

    //    //    #region Root Properties

    //    //    public static readonly PropertyInfo<long> IDProperty = RegisterProperty<long>(c => c.ID);
    //    //    public long ID
    //    //    {
    //    //        get { return GetProperty(IDProperty); }
    //    //        private set { LoadProperty(IDProperty, value); }
    //    //    }

    //    //    public static readonly PropertyInfo<long> ParentIDProperty = RegisterProperty<long>(c => c.ParentID);
    //    //    public long ParentID
    //    //    {
    //    //        get { return GetProperty(ParentIDProperty); }
    //    //        set { SetProperty(ParentIDProperty, value); }
    //    //    }

    //    //    public static readonly PropertyInfo<decimal> LowAmountProperty = RegisterProperty<decimal>(c => c.LowAmount);
    //    //    public decimal LowAmount
    //    //    {
    //    //      get { return GetProperty(LowAmountProperty); }
    //    //      private set { SetProperty(LowAmountProperty, value); }
    //    //    }

    //    //    public static readonly PropertyInfo<decimal> HighAmountProperty = RegisterProperty<decimal>(c => c.HighAmount);
    //    //    public decimal HighAmount
    //    //    {
    //    //      get { return GetProperty(HighAmountProperty); }
    //    //      private set { SetProperty(HighAmountProperty, value); }
    //    //    }

    //    //    public static readonly PropertyInfo<decimal> PercentageProperty = RegisterProperty<decimal>(c => c.Percentage);
    //    //    public decimal Percentage
    //    //    {
    //    //      get { return GetProperty(PercentageProperty); }
    //    //      private set { SetProperty(PercentageProperty, value); }
    //    //    }

    //    //    public static readonly PropertyInfo<DateTime?> CreationDateProperty = RegisterProperty<DateTime?>(c => c.CreationDate);
    //    //    public DateTime? CreationDate
    //    //    {
    //    //        get { return GetProperty(CreationDateProperty); }
    //    //        private set { SetProperty(CreationDateProperty, value); }
    //    //    }

    //    //    public static readonly PropertyInfo<string> CreationUserProperty = RegisterProperty<string>(c => c.CreationUser);
    //    //    public string CreationUser
    //    //    {
    //    //        get { return GetProperty(CreationUserProperty); }
    //    //        private set { SetProperty(CreationUserProperty, value); }
    //    //    }

    //    //    public static readonly PropertyInfo<DateTime?> LastModificationDateProperty = RegisterProperty<DateTime?>(c => c.LastModificationDate);
    //    //    public DateTime? LastModificationDate
    //    //    {
    //    //        get { return GetProperty(LastModificationDateProperty); }
    //    //        private set { SetProperty(LastModificationDateProperty, value); }
    //    //    }

    //    //    public static readonly PropertyInfo<string> LastModificationUserProperty = RegisterProperty<string>(c => c.LastModificationUser);
    //    //    public string LastModificationUser
    //    //    {
    //    //        get { return GetProperty(LastModificationUserProperty); }
    //    //        private set { SetProperty(LastModificationUserProperty, value); }
    //    //    }

    //    //    public static readonly PropertyInfo<byte[]> RowTimestampProperty = RegisterProperty<byte[]>(c => c.RowTimestamp);
    //    //    public byte[] RowTimestamp
    //    //    {
    //    //        get { return GetProperty(RowTimestampProperty); }
    //    //        private set { LoadProperty(RowTimestampProperty, value); }
    //    //    }

    //    //    #endregion

    //    //    #endregion

    //    //    #region Search Functions

    //    //    #region GetVolumeDiscount

    //    //    [Serializable]
    //    //    internal class GetVolumeDiscountByKeyCriteria : CriteriaBase<GetVolumeDiscountByKeyCriteria>, Customer._VolumeDiscount.ISearchCriteria
    //    //    {
    //    //        public long ID { get; set; }
    //    //        public string Collation { get; set; }
    //    //        public Expression<Func<Models.ClientRabaisVolume, bool>> GetWhereExpression()
    //    //        {
    //    //            return (x => x.ClientRabaisVolumeID == this.ID);
    //    //        }
    //    //        public GetVolumeDiscountByKeyCriteria(long id, string collation)
    //    //        {
    //    //            this.ID = id;
    //    //            this.Collation = collation;
    //    //        }
    //    //    }
    //    //    public static Customer._VolumeDiscount GetVolumeDiscount(long id, string collation)
    //    //    {
    //    //        return DataPortal.Fetch<Customer._VolumeDiscount>(new GetVolumeDiscountByKeyCriteria(id, collation));
    //    //    }
    //    //    public static Task<Customer._VolumeDiscount> GetVolumeDiscountAsync(long id, string collation)
    //    //    {
    //    //        return DataPortal.FetchAsync<Customer._VolumeDiscount>(new GetVolumeDiscountByKeyCriteria(id, collation));
    //    //    }

    //    //    #endregion

    //    //    #region GetSpecificVolumeDiscount

    //    //    [Serializable]
    //    //    internal class GetSpecificVolumeDiscountCriteria : CriteriaBase<GetSpecificVolumeDiscountCriteria>, Customer._VolumeDiscount.ISearchCriteria
    //    //    {
    //    //        public long ID { get; set; }
    //    //        public byte[] RowTimestamp { get; set; }
    //    //        public string Collation { get; set; }
    //    //        public Expression<Func<Models.ClientRabaisVolume, bool>> GetWhereExpression()
    //    //        {
    //    //            return (x => x.ClientRabaisVolumeID == this.ID);
    //    //        }
    //    //        public GetSpecificVolumeDiscountCriteria(long id, byte[] RowTimestamp, string collation)
    //    //        {
    //    //            this.ID = id;
    //    //            this.RowTimestamp = RowTimestamp;
    //    //            this.Collation = collation;
    //    //        }
    //    //    }
    //    //    public static Customer._VolumeDiscount GetSpecificVolumeDiscount(long id, byte[] RowTimestamp, string collation)
    //    //    {
    //    //        return DataPortal.Fetch<Customer._VolumeDiscount>(new GetSpecificVolumeDiscountCriteria(id, RowTimestamp, collation));
    //    //    }
    //    //    public static Task<Customer._VolumeDiscount> GetSpecificVolumeDiscountAsync(long id, byte[] RowTimestamp, string collation)
    //    //    {
    //    //        return DataPortal.FetchAsync<Customer._VolumeDiscount>(new GetSpecificVolumeDiscountCriteria(id, RowTimestamp, collation));
    //    //    }

    //    //    #endregion

    //    //    #endregion

    //    //    #region Model Mappings

    //    //    private void FillObjectFromModel(Models.ClientRabaisVolume model)
    //    //    {
    //    //        using (BypassPropertyChecks)
    //    //        {
    //    //            LoadProperty(IDProperty, model.ClientRabaisVolumeID);
    //    //            LoadProperty(ParentIDProperty, model.ClientID);
    //    //            LoadProperty(LowAmountProperty, model.ClientRabaisVolumeMontantInf);
    //    //            LoadProperty(HighAmountProperty, model.ClientRabaisVolumeMontantSup);
    //    //            LoadProperty(PercentageProperty, model.ClientRabaisVolumePourc);
    //    //            LoadProperty(CreationDateProperty, model.CreationDate);
    //    //            LoadProperty(CreationUserProperty, model.CreationUser);
    //    //            LoadProperty(LastModificationDateProperty, model.LastModificationDate);
    //    //            LoadProperty(LastModificationUserProperty, model.LastModificationUser);
    //    //            LoadProperty(RowTimestampProperty, model.RowTimestamp);
    //    //        }
    //    //    }
    //    //    private void FillModelFromObject(Models.ClientRabaisVolume model)
    //    //    {
    //    //        if (this.IsChild && this.Parent is Customer._VolumeDiscount && this.Parent.Parent is Customer)
    //    //            model.ClientID = ((Customer)this.Parent.Parent).ID;
    //    //        else
    //    //            model.ClientID = this.ParentID;

    //    //        model.ClientRabaisVolumeMontantInf = this.LowAmount;
    //    //        model.ClientRabaisVolumeMontantSup = this.HighAmount;
    //    //        model.ClientRabaisVolumePourc = this.Percentage;
    //    //        model.CreationDate = null;
    //    //        model.CreationUser = null;
    //    //        model.LastModificationDate = null;
    //    //        model.LastModificationUser = null;
    //    //        model.RowTimestamp = this.RowTimestamp;
    //    //    }

    //    //    #endregion

    //    //    #region DataPortal Functions

    //    //    internal class DataPortal_FetchArgs
    //    //    {
    //    //        public string DefaultCollection { get; set; }
    //    //        public Models.ClientRabaisVolume Model { get; set; }
    //    //    }
    //    //    internal interface ISearchCriteria
    //    //    {
    //    //        string Collation { get; set; }
    //    //        Expression<Func<Models.ClientRabaisVolume, bool>> GetWhereExpression();
    //    //    }
    //    //    internal static Base.CORE.DataLayer.IDbContextBase DomainDrivenDesignBoundedContext
    //    //    {
    //    //        get { return new DataLayer.EnterpriseResourcePlanning.CustomerContext(); }
    //    //    }

    //    //    internal static Customer._VolumeDiscount FetchChild(long? id, Models.ClientRabaisVolume model, string collation)
    //    //    {
    //    //        if (id == null) return null;
    //    //        if (model != null) return DataPortal.FetchChild<Customer._VolumeDiscount>(new DataPortal_FetchArgs() { Model = model, DefaultCollection = collation });
    //    //        return DataPortal.FetchChild<Customer._VolumeDiscount>(new GetVolumeDiscountByKeyCriteria((long)id, collation));
    //    //    }

    //    //    protected override void DataPortal_Create()
    //    //    {
    //    //        CreateObject();
    //    //    }
    //    //    protected override void Child_Create()
    //    //    {
    //    //        base.Child_Create();
    //    //        CreateObject();
    //    //    }
    //    //    private void CreateObject()
    //    //    {
    //    //        this.CreationDate = System.DateTime.Now;
    //    //        this.CreationUser = Csla.ApplicationContext.User.Identity.Name;
    //    //    }

    //    //    private void DataPortal_Fetch(ISearchCriteria criteria)
    //    //    {
    //    //        FetchModel(criteria);
    //    //    }
    //    //    private void Child_Fetch(ISearchCriteria criteria)
    //    //    {
    //    //        FetchModel(criteria);
    //    //    }
    //    //    private void FetchModel(ISearchCriteria criteria)
    //    //    {
    //    //        using (Base.CORE.DataLayer.IDbContextBase _context = DomainDrivenDesignBoundedContext)
    //    //        {
    //    //            //Selecting + Including
    //    //            var query = _context.GetQuery<Models.ClientRabaisVolume>();

    //    //            // Filtering
    //    //            if (criteria.GetWhereExpression() != null)
    //    //                query = query.Where(criteria.GetWhereExpression());

    //    //            // Executing
    //    //            var model = query.Single();
    //    //            if (model != null)
    //    //            {
    //    //                // Building
    //    //                DataPortal_FetchArgs args = new DataPortal_FetchArgs() { Model = model, DefaultCollection = criteria.Collation };
    //    //                FetchModel(args);
    //    //            }
    //    //        }
    //    //    }

    //    //    private void DataPortal_Fetch(DataPortal_FetchArgs args)
    //    //    {
    //    //        FetchModel(args);
    //    //    }
    //    //    private void Child_Fetch(DataPortal_FetchArgs args)
    //    //    {
    //    //        FetchModel(args);
    //    //    }
    //    //    private void FetchModel(DataPortal_FetchArgs args)
    //    //    {
    //    //        this.DefaultCollation = args.DefaultCollection;
    //    //        FillObjectFromModel(args.Model);
    //    //    }

    //    //    protected override void DataPortal_Insert() { InsertModel(); }
    //    //    private void Child_Insert() { InsertModel(); }
    //    //    private void InsertModel()
    //    //    {
    //    //        using (Base.CORE.DataLayer.IDbContextBase _context = DomainDrivenDesignBoundedContext)
    //    //        {
    //    //            /*
    //    //            var query = from o in _context.GetQuery<Models.ClientNote>()
    //    //                        where o.Code == this.Code
    //    //                        select o;
    //    //            if (query.Count() > 0)
    //    //                throw new DataPortalException("Code already exists", this);
    //    //            */

    //    //            Models.ClientRabaisVolume model = new Models.ClientRabaisVolume();
    //    //            FillModelFromObject(model);

    //    //            _context.Add<Models.ClientRabaisVolume>(model);
    //    //            _context.SaveChanges();

    //    //            FetchModel(new GetVolumeDiscountByKeyCriteria(model.ClientRabaisVolumeID, this.DefaultCollation));
    //    //        }
    //    //    }

    //    //    protected override void DataPortal_Update() { UpdateModel(); }
    //    //    private void Child_Update() { UpdateModel(); }
    //    //    private void UpdateModel()
    //    //    {
    //    //        using (Base.CORE.DataLayer.IDbContextBase _context = DomainDrivenDesignBoundedContext)
    //    //        {
    //    //            var query = from o in _context.GetQuery<Models.ClientRabaisVolume>()
    //    //                        where o.ClientRabaisVolumeID == this.ID
    //    //                        where o.RowTimestamp == this.RowTimestamp
    //    //                        select o;

    //    //            var model = query.SingleOrDefault();
    //    //            if (model == null)
    //    //                throw new DataPortalException("ConcurrencyCheck Failed", this);

    //    //            FillModelFromObject(model);

    //    //            _context.Update<Models.ClientRabaisVolume>(model);
    //    //            _context.SaveChanges();

    //    //            FetchModel(new GetVolumeDiscountByKeyCriteria(model.ClientRabaisVolumeID, this.DefaultCollation));
    //    //        }
    //    //    }

    //    //    protected override void DataPortal_DeleteSelf() { DeleteModel(); }
    //    //    private void Child_DeleteSelf() { DeleteModel(); }
    //    //    private void DeleteModel()
    //    //    {
    //    //        using (Base.CORE.DataLayer.IDbContextBase _context = DomainDrivenDesignBoundedContext)
    //    //        {
    //    //            var query = from o in _context.GetQuery<Models.ClientRabaisVolume>()
    //    //                        where o.ClientRabaisVolumeID == this.ID
    //    //                        where o.RowTimestamp == this.RowTimestamp
    //    //                        select o;

    //    //            var model = query.SingleOrDefault();
    //    //            if (model == null)
    //    //                throw new DataPortalException("ConcurrencyCheck Failed", this);

    //    //            _context.Delete<Models.ClientRabaisVolume>(model);
    //    //            _context.SaveChanges();

    //    //        }
    //    //    }

    //    //    #endregion

    //    //    #region Validation

    //    //    protected override void AddBusinessRules()
    //    //    {
    //    //        base.AddBusinessRules();
    //    //    }

    //    //    #endregion

    //    //}

    //    #endregion
    //}

    #endregion
}

}

jonnybee commented 8 years ago

I'd rather prefer to get the code in a github repo or a zip file.

The key issue is that you do not want to load the data until the property getter is called in the UI.

One key mistake is if you have business rules that use the property as input. That will trigger a fetch of the property value when the the rule engine execute rules. To some extent that can be avaided if your rule inherit from PropertyRule and you set CanRunOnServer to false. Just put a breakpoint inside the property getter to identify what code is calling the property getter.

So the key issue is to identify which code is calling the property getter of the lazy loaded object.

For my own preference I would really consider to only send the "id values" as parameter on DataPortal.XYZ calls. Say - you are tasked to create a movile version or universal app - and now all of a sudden you need a "remote" portal and you must send the entire object over the wire - rather than just the actual values.

Ex:

        public static _ContactCollection FetchChildren(Customer parent)
        {
            return DataPortal.Fetch<Customer._ContactCollection>(parent);
        }
        private void DataPortal_Fetch(Customer parent)

Should rather have been:

        public static _ContactCollection FetchChildren(Customer parent)
        {
            return DataPortal.Fetch<Customer._ContactCollection>(parent.ID);
        }
        private void DataPortal_Fetch(long id)