Tuesday 29 March 2011

EF4 and bulk delete


When you want to delete records in EF4 typically you load the objects and delete them in the database context. This is a little slow. Microsoft recommends in such cases to use a stored procedure which I find not so cool. Here is an alternative way of doing this:



public void DeleteAll(IQueryable clause) where TEntity : class
{
string sqlClause = GetClause(clause);
this.context.ExecuteStoreCommand(string.Format(CultureInfo.InvariantCulture, "DELETE {0}", sqlClause));
}


private string GetClause(IQueryable clause) where TEntity : class
{
string snippet = "FROM [dbo].[";

string sql = ((ObjectQuery)clause).ToTraceString();
string sqlFirstPart = sql.Substring(sql.IndexOf(snippet));

sqlFirstPart = sqlFirstPart.Replace("AS [Extent1]", "");
sqlFirstPart = sqlFirstPart.Replace("[Extent1].", "");

// The above code works well for clauses like
// IQueryable clause = this.databaseContext.Query().Where(v => v.ModelRunId == 1);
// BUT as soon as you replace "v => v.ModelRunId == 1" with "v => v.ModelRunId == myId" you will get sql looking like:
// "SELECT \r\n[Extent1].[LOSS_FILE_ID] AS [LOSS_FILE_ID], \r\n ...WHERE [Extent1].[MODEL_RUN_ID] = @p__linq__0"
// To evaluate @p__linq__0 you need to use the code below:
foreach (ObjectParameter Param in (((ObjectQuery)clause)).Parameters) {
switch (Param.ParameterType.FullName)
{
case "System.Int32":
sqlFirstPart = sqlFirstPart.Replace("@"+Param.Name, Param.Value.ToString());
break;
case "System.String":
sqlFirstPart = sqlFirstPart.Replace("@"+Param.Name, "'"+Param.Value.ToString().Replace("'","''")+"'");
break;

default:
throw new NotImplementedException("Parameter conversion for this type is not yet implemented");
}
}
return sqlFirstPart;
}


Now the delete command can be called using a fluent linq clause in the following way:



IQueryable clause = this.databaseContext.Query().Where(v => v.ModelRunId.Value == ModelRunId);
this.databaseContext.DeleteAll(clause);

Thursday 10 March 2011

Paired programming: How to use Data Annotations in WPF without throwing Validation exceptions


We want to add simple data validation rules directly on the property within the view model. Data annotation provides attributes designed to do exactly this. There are some great websites that describe how to do this

From http://msdn.microsoft.com/en-us/library/dd901590(v=vs.95).aspx we have a great example of how this is done in Silverlight using a sdk which includes a modified datagrid and a DescriptionViewer ( which I will return to later). Within this website we can find a wide range of simple validation attributes as illustrated in the sample shown below:



public class Product
{
[Display(Name="Product Number")]
[Range(0, 5000)]
public int ProductID { get; set; }

[Display(Name="Name")]
[Required]
public string ProductName { get; set; }

[Display(Name="Price")]
[DataType(DataType.Currency)]
public double ListPrice { get; set; }

[EnumDataType(typeof(ProductColor))]
public ProductColor Color { get; set; }

[Display(Name="Available")]
public bool InStock { get; set; }

public Product() { }

public Product(int _productID, string _productName,
double _listPrice, ProductColor _color, bool _inStock)
{
this.ProductID = _productID;
this.ProductName = _productName;
this.ListPrice = _listPrice;
this.Color = _color;
this.InStock = _inStock;
}
}



It is also possible to validate regular expressions eg

[RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage ="….")]

We want to incorporate this into our view model because these attributes help to document the property and provide a mechanism to validate against. Here's another great web site that goes through the steps of adding this to a WPF application:

http://outcoldman.ru/en/blog/show/259

If we run through the steps described in these websites and combine with our modified INotifyPropertyChanged base class that I described in my last blog entry we end up with a model-view that looks like:



using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace Ccp.Wpf.Infrastructure.Entities
{
public class FranchiseStepPayouts : ModelSettingsBase
{
private double franchiseDeductiblePercentage;
[Display(Name = "Franchise deductible percentage", Description = "Blanket Franchise deductible percentage used to bla bla")]
[Range(0, 100, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
public double FranchiseDeductiblePercentage
{
get
{
return franchiseDeductiblePercentage;
}
set
{
Validator.ValidateProperty(value,
new ValidationContext(this, null, null) { MemberName = "FranchiseDeductiblePercentage" });
franchiseDeductiblePercentage = value;
RaisePropertyChanged(() => FranchiseDeductiblePercentage);
}
}




The validation happens on line

Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "FranchiseDeductiblePercentage" });

The corresponding view looks like:



<UserControl.Resources>
<local:EnumMatchToBooleanConverter x:Key="enumConverter" />
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<TextBlock Foreground="Red" FontSize="20">*</TextBlock>
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>


...



<!-- Franchise -->
<StackPanel Orientation="Horizontal" Grid.Column="1" Grid.Row="0">
<TextBox Text="{Binding FranchiseDeductiblePercentage, Mode= TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}"
Width="100"
Validation.ErrorTemplate="{StaticResource validationTemplate}"
Style="{StaticResource textBoxInError}" />
<Label Content="%" Height="23" VerticalAlignment="Top" />
</StackPanel>


Breaking this down into parts: The text box contains a binding with an a term "ValidatesOnExceptions=true" This tells the view that it should listen for Validation exceptions that are thrown in the view model. This happens in the setter with the Validator.ValidateProperty. So in our case we have decorated our FranchiseDeductiblePercentage with

[Display(Name = "Franchise deductible percentage", Description = "Blanket Franchise deductible percentage used to bla bla")]
[Range(0, 100, ErrorMessage = "Value for {0} must be between {1} and {2}.")]

This means that if we enter a value outside of the range 0 to 100 inclusive then an execption will be raised when we validate in the code below:

Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "FranchiseDeductiblePercentage" });

Then in the textbox we specified a validation template as follows:

Validation.ErrorTemplate="{StaticResource validationTemplate}"

The definition of this template looks like:



<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<TextBlock Foreground="Red" FontSize="20">*</TextBlock>
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>


Actually we don't need to overwrite the default validation template but it's interesting to see how this is done so that we have more control over what we are doing. But we want to get some kind of message that describes why the entered value is wrong. This is done by creating a trigger that sets a Tooltip when an error occurs. This is done as shown below:



<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>


Notice the very interesting binding path, in particular

Path=(Validation.Errors)[0].ErrorContent}

If I understand this correctly the view is listening for a validation error and then is able to resolve Validation.Errors. The display and range attributes set metadata that the Validation object is able to reflect upon and incorporate in a formatted error message. In our case we have 2 attributes

[Display(Name = "Franchise deductible percentage", Description = "Blanket Franchise deductible percentage used to bla bla")]
[Range(0, 100, ErrorMessage = "Value for {0} must be between {1} and {2}.")]

This will build a tooltip that looks like "Value for Franchise deductible percentage must be between 0 and 100."

Our next step was to think about adding a glyph or information icon that contains the description of the field so that the user has a more precise description of what the field is about. This turned out to be a little tricky. You could create some property that have the decription eg:



public double FranchiseDeductiblePercentageDescription
{
get
{
ValidationContext x = new ValidationContext(this, null, null) { MemberName = "FranchiseDeductiblePercentage" };
return x.DisplayName;
}



But this means a lot of extra typing. We found more information about the definition of the DisplayAttribute at:



http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.aspx

We decided to use reflector to disassemble the Silverlight SDK to figure out how they implemented the DisplayViewer. The assembly was located in

C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Libraries\Client\System.Windows.Controls.Data.Input.dll

There was a lot of code and we managed to get quite far but decided to refine our google search criteria to include the term converter. And we found an example but I can't remember from which web site. After some adjustments the viewer looks like




namespace Ccp.Wpf.Infrastructure.Converter
{
[ValueConversion(typeof(String), typeof(String))]
public class MetaDataDisplayNameConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string result = "";

if (value != null)
{
Type sourceType = value.GetType();
var propertyName = parameter as string;

if (propertyName != null)
{
var propertyInfo = sourceType.GetProperty(propertyName);

foreach (DisplayAttribute attr in propertyInfo.GetCustomAttributes(typeof(DisplayAttribute), true))
{
result = attr.Description;
}
}
}

return result;
}


public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}


This converted is used in the following way:

<Image Source="/Ccp.Wpf.Infrastructure;Component/Images/Cute-Ball-Info-icon.png" Height="23" Stretch="Uniform" VerticalAlignment="Top"
ToolTip="{Binding Converter={StaticResource metaDataDisplayNameConverter}, ConverterParameter=FranchiseDeductiblePercentage}"/>

By not specifying a parameter in the Binding clause we pass the data context to the converter. The ConverterParameter specifies a string that we should search for when we make reflection. Reflection is a slow operation so we if we use this converter in large forms we should add a cache in the way of a static private property in the converter. This could be a Hashtable or a dictionary. Coming back to the validation mechanism. There are disadvantages to throwing exceptions in setters. These are described quite well by http://outcoldman.ru/en/blog/show/259

The main problem is that exceptions should only be thrown when an unforeseen condition is met. So we want to use data annotations without throwing exceptions in the setter. It turns out that these is another binding property called

ValidatesOnDataErrors=True

When this is set the view looks for an implementation of IDataErrorInfo. So this means instead of looking for an exception we are listening to an interface. This means that our binding looks like:



<TextBox Text="{Binding FranchiseDeductiblePercentage, Mode= TwoWay, ValidatesOnDataErrors=True, NotifyOnValidationError=true}"
Width="100"
Validation.ErrorTemplate="{StaticResource validationTemplate}"
Style="{StaticResource textBoxInError}" />


We found an implementation of IDataErrorInfo at

http://stackoverflow.com/questions/3739059/prism-idataerrorinfo-validation-with-dataannotation-on-viewmodel-entities

After some small modifications our implementation looked like:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.Linq.Expressions;

namespace Ccp.Contracts.UI
{
public class DataErrorInfo : NotificationObject, IDataErrorInfo
{
public string Error
{
get
{
return null;
}
}
string IDataErrorInfo.this[string columnName]
{
get
{
return ValidateProperty(columnName);
}
}
protected virtual string ValidateProperty(string columnName)
{
// get cached property accessors
var propertyGetters = GetPropertyGetterLookups(GetType());
if (propertyGetters.ContainsKey(columnName))
{
// read value of given property
var value = propertyGetters[columnName](this);
// run validation
var results = new List();
var vc = new ValidationContext(this, null, null) { MemberName = columnName };
Validator.TryValidateProperty(value, vc, results);
// transpose results
var errors = Array.ConvertAll(results.ToArray(), o => o.ErrorMessage);
return string.Join(Environment.NewLine, errors);
}
return string.Empty;
}
private static readonly Dictionary<string, object>
PropertyLookupCache = new Dictionary<string, object>();
private static Dictionary<string, Func<object, object>> GetPropertyGetterLookups(Type objType)
{
var key = objType.FullName ?? "";
if (!PropertyLookupCache.ContainsKey(key))
{
var o = objType.GetProperties().Where(p => GetValidations(p).Length != 0).ToDictionary(p => p.Name, CreatePropertyGetter);
PropertyLookupCache[key] = o;
return o;
}
return (Dictionary<string, Func>object, object>>)PropertyLookupCache[key];
}
private static Func<object, object> CreatePropertyGetter(PropertyInfo propertyInfo)
{
var instanceParameter = Expression.Parameter(typeof(object), "instance");
var expression = Expression.Lambda<Func<object, object>>(Expression.ConvertChecked(Expression.MakeMemberAccess(Expression.ConvertChecked(instanceParameter, propertyInfo.DeclaringType), propertyInfo), typeof(object)), instanceParameter);
var compiledExpression = expression.Compile(); return compiledExpression;
}
private static ValidationAttribute[] GetValidations(PropertyInfo property)
{
return (ValidationAttribute[])property.GetCustomAttributes(typeof(ValidationAttribute), true);
}
}
}


Notice that we inherit from our Notification object, this is so that we can use a func instead of a string to identify which property has changed. Then all we need to do to inherit from this base class in our view model. In our case we have an intermediate base class because we are implementing a MVVMC



namespace Ccp.Contracts.Model
{
///
/// This classes could be generated from a T4 template (pocos)
///

public abstract class ModelSettingsBase : DataErrorInfo
{
///
/// Just an example of a field
///

public string Name
{
get { return this.GetType().Name; }
}

public abstract void Save(int ModelRunId);
public abstract bool Validate();
}
}


Then



namespace Ccp.Wpf.Infrastructure.Entities
{
public class FranchiseStepPayouts : ModelSettingsBase
{
private double franchiseDeductiblePercentage;
[Display(Name = "Franchise deductible percentage", Description = "Blanket Franchize deductible percentage")]
[Range(0, 100, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
public double FranchiseDeductiblePercentage
{
get
{
return franchiseDeductiblePercentage;
}
set
{
//Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "FranchiseDeductiblePercentage" });

franchiseDeductiblePercentage = value;
RaisePropertyChanged(() => FranchiseDeductiblePercentage);
}
}


And now it works without exceptions

Friday 4 March 2011

A day of WPF paired programming

Here’s a journal of code that was written in a paired programming session last week…

We started by looking at the FranchiseStepPayoutFunction Control. This control has some interesting behavior. Part of the control consists of a table of LowerLimit,UpperLimit and Payout. We would like that the Upper Limit of Row n populates the lower limit of Row n+1. We would also like to style the grid with characters like "-" between the upper and lower limit and a % for the payout.

Starting with the xaml, we decided to use a ItemControl to solve this:

        <ItemsControl ItemsSource="{Binding StepPayouts}" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="4">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Vertical" />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
                        <TextBox Text="{Binding LowerStepLimit, Mode= TwoWay}" Width="100" Margin="0 0 10 0" />
                        <Label Content="-" Height="23" VerticalAlignment="Top" />
                        <TextBox Text="{Binding UpperStepLimit, Mode= TwoWay}" Width="100" Margin="0 0 10 0"/>
                        <TextBox Text="{Binding Payout, Mode= TwoWay}" Width="100" />
                        <Label Content="%" Height="23" VerticalAlignment="Top" />
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

This is bound to a List

    public class FranchiseStepPayouts : ModelSettingsBase
    {
        public List<StepPayout> StepPayouts { get; private set; }

        public FranchiseStepPayouts()
        {
            StepPayouts = new List<StepPayout>();

            // Populate 4 columns
            for (int i = 0; i < 4; i++)
            {
                StepPayout s = new StepPayout(0, 0, 0);
                s.UpperStepLimitChangedEvent += new StepPayout.UpperStepLimitChangedHandler(s_UpperStepLimitChangedEvent);
                StepPayouts.Add(s);
            }
        }

...
    }

The StepPayout looks like:

namespace Ccp.Wpf.Infrastructure.Entities
{
    public class StepPayout : NotificationObject
    {

        public delegate void PayoutChangedHandler(object sender);
        public event PayoutChangedHandler PayoutChangedEvent;
        virtual protected void PayoutChangedRaiseEvent()
        {
            if (PayoutChangedEvent != null)
            {
                PayoutChangedEvent(this);
            }
        }

        private double payout;
        public double Payout
        {
            get
            {
                return this.payout;
            }
            set
            {
                payout = value;
                RaisePropertyChanged(()=>Payout);
                PayoutChangedRaiseEvent();
            }
        }
        .. dito for Lower and Upper Step Payout limits

        public StepPayout(double UpperStepLimit, double LowerStepLimit, double Payout)
        {
            this.lowerStepLimit = LowerStepLimit;
            this.upperStepLimit = UpperStepLimit;
            this.payout = Payout;
        }
    }
}

Notice that we used a home made NotificationObject, this is so that we don't need to write a string in the RaisePropertyChanged field. Which means, instead of writing
                RaisePropertyChanged("Payout");
we can write
                RaisePropertyChanged(()=>Payout);

We copied the code that makes this possible from Prism. Our home made class for this looks like:

namespace Ccp.Wpf.Infrastructure.Helpers
{
    public class NotificationObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
        {
            var propertyName = ExtractPropertyName(propertyExpression);
            this.RaisePropertyChanged(propertyName);
        }

        public static string ExtractPropertyName<T>(Expression<Func<T>> propertyExpression)
        {
            if (propertyExpression == null)
            {
                throw new ArgumentNullException("propertyExpression");
            }
            var memberExpression = propertyExpression.Body as MemberExpression;
            if (memberExpression == null)
            {
                throw new ArgumentException("NotMemberAccessExpression_Exception", "propertyExpression");
            }
            var property = memberExpression.Member as PropertyInfo;
            if (property == null)
            {
                throw new ArgumentException("ExpressionNotProperty_Exception", "propertyExpression");
            }
            var getMethod = property.GetGetMethod(true);
            if (getMethod.IsStatic)
            {
                throw new ArgumentException("StaticExpression_Exception", "propertyExpression");
            }
            return memberExpression.Member.Name;
        }
    }
}

Our application does not need to be localizable so we removed the references to resources.

The next thing that we looked at was the list that we used in the view model

    public class FranchiseStepPayouts : ModelSettingsBase
    {
        public List<StepPayout> StepPayouts { get; private set; }

This works well provided the number of items in the list does not change. If the number of items in the list changes you need to replace List with ObservableCollection and you need to RaisePropertyChanged so that the UI know it needs to update. If the list was very large this would lead to an avalanche of events that would make the UI unresponsive, in that case it is better to create the observable list and set the entire property in one go. In our case we only have a few items. This makes the code look like the following.

    public class FranchiseStepPayouts : ModelSettingsBase
    {

        private ObservableCollection<StepPayout> stepPayouts;
        public ObservableCollection<StepPayout> StepPayouts
        {
            get
            {
                return stepPayouts;
            }
            private set
            {
                stepPayouts = value;
                RaisePropertyChanged(() => StepPayouts);
            }
        }

        private PayOutFunction payoutFunction;

        public PayOutFunction PayoutFunction
        {
            get
            {
                return payoutFunction;
            }
            set
            {
                payoutFunction = value;
                RaisePropertyChanged(() => PayoutFunction);
            }
        }

We register the events in the constructor

        public FranchiseStepPayouts()
        {
            StepPayouts = new ObservableCollection<StepPayout>();

            // Populate 4 columns
            for (int i = 0; i < 4; i++)
            {
                StepPayout s = new StepPayout(0, 0, 0);
                s.UpperStepLimitChangedEvent += new StepPayout.UpperStepLimitChangedHandler(s_UpperStepLimitChangedEvent);
                StepPayouts.Add(s);
            }
        }

We respond to the events by replacing the lower limit of the n+1 column
        void s_UpperStepLimitChangedEvent(object sender)
        {
            for (int i = 0; i < this.StepPayouts.Count - 1; i++)
            {
                this.StepPayouts[i + 1].LowerStepLimit = this.StepPayouts[i].UpperStepLimit;
            }
        }

Next adding an auto hide function with checkbox

    public class FranchiseStepPayouts : ModelSettingsBase
    {

        private bool isPayoutFunctionVisible;

        public bool IsPayoutFunctionVisible
        {
            get
            {
                return isPayoutFunctionVisible;
            }
            set
            {
                isPayoutFunctionVisible = value;
                RaisePropertyChanged(() => IsPayoutFunctionVisible);
            }
        }

<UserControl x:Class="Ccp.Wpf.Infrastructure.Controls.FranchiseStepPayoutsView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:Ccp.Wpf.Infrastructure.Controls"
             xmlns:converter="clr-namespace:Ccp.Wpf.Infrastructure.Converter"
             mc:Ignorable="d"
             d:DesignWidth="500">
    <UserControl.Resources>
        <local:EnumMatchToBooleanConverter x:Key="enumConverter" />
    </UserControl.Resources>

    <StackPanel Orientation="Vertical" Grid.Column="0" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
        <CheckBox Content="Japanise Payout Function" IsChecked="{Binding IsPayoutFunctionVisible}"/>
        <GroupBox Header="Japanise Payout Function" Visibility="{Binding IsPayoutFunctionVisible, Converter={converter:BoolToVisibilityConverter FalseValue=Collapsed}}" VerticalAlignment="Top" HorizontalAlignment="Left">
            <Grid>

                <!-- Content -->

            </Grid>
        </GroupBox>
    </StackPanel>
</UserControl>

namespace Ccp.Wpf.Infrastructure.Converter
{
    public class BoolToVisibilityConverter : MarkupExtension, IValueConverter
    {
        public BoolToVisibilityConverter()
        {
            TrueValue = Visibility.Visible;
            FalseValue = Visibility.Collapsed;
        }

        public Visibility TrueValue { get; set; }
        public Visibility FalseValue { get; set; }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool val = System.Convert.ToBoolean(value);
            return val ? TrueValue : FalseValue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return TrueValue.Equals(value) ? true : false;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }
    }
}

Next here is the implementation of a radio button

<UserControl x:Class="Ccp.Wpf.Infrastructure.Controls.FranchiseStepPayoutsView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:Ccp.Wpf.Infrastructure.Controls"
             xmlns:converter="clr-namespace:Ccp.Wpf.Infrastructure.Converter"
             mc:Ignorable="d"
             d:DesignWidth="500">
    <UserControl.Resources>
        <local:EnumMatchToBooleanConverter x:Key="enumConverter" />
    </UserControl.Resources>
...

                <StackPanel Orientation="Vertical"  HorizontalAlignment="Left"  Grid.Row="0" Grid.RowSpan="2" Grid.Column="0" Width="100">
                    <StackPanel Orientation="Horizontal"  HorizontalAlignment="Left"  >
                        <RadioButton Content="Franchise" GroupName="Franchise" Height="23"
                             IsChecked="{Binding Path=PayoutFunction, Mode=TwoWay,
                                                 Converter={StaticResource enumConverter},
                                                 ConverterParameter=Franchise}"  />
                        <Label Content=" " Height="23" VerticalAlignment="Top" />
                    </StackPanel>
                    <StackPanel Orientation="Horizontal"  HorizontalAlignment="Left"  >
                        <RadioButton Content="Step Payout" GroupName="Franchise" Height="23"
                             IsChecked="{Binding Path=PayoutFunction, Mode=TwoWay,
                                                 Converter={StaticResource enumConverter},
                                                 ConverterParameter=StepPayout}"  />
                        <Label Content=" " Height="23" VerticalAlignment="Top" />
                    </StackPanel>
                </StackPanel>
...

            </Grid>
        </GroupBox>
    </StackPanel>
</UserControl>

namespace Ccp.Wpf.Infrastructure.Controls
{
    public class EnumMatchToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType,
                              object parameter, CultureInfo culture)
        {
            if (value == null || parameter == null)
                return false;

            string checkValue = value.ToString();
            string targetValue = parameter.ToString();
            return checkValue.Equals(targetValue,
                     StringComparison.InvariantCultureIgnoreCase);
        }

        public object ConvertBack(object value, Type targetType,
                                  object parameter, CultureInfo culture)
        {
            if (value == null || parameter == null)
                return null;

            bool useValue = (bool)value;
            string targetValue = parameter.ToString();
            if (useValue)
                return Enum.Parse(targetType, targetValue);

            return null;
        }
    }
}

namespace Ccp.Wpf.Infrastructure.Entities
{
    public enum PayOutFunction
    {
        None,
        Franchise,
        StepPayout
    }
}

namespace Ccp.Wpf.Infrastructure.Entities
{
    public class FranchiseStepPayouts : ModelSettingsBase
    {
        private PayOutFunction payoutFunction;

        public PayOutFunction PayoutFunction
        {
            get
            {
                return payoutFunction;
            }
            set
            {
                payoutFunction = value;
                RaisePropertyChanged(() => PayoutFunction);
            }
        }

Next here is how to call the wpf windows with a foriegn key (ExposureDataId)

Use the container to access the modelview of the WPF user control

Public Class frmCatFocusMain
    Implements IDisposable
..
   Private _container As CompositionContainer
..
    Public Sub New()

        'Dim directoryCatalog As New DirectoryCatalog(".")
        Dim iAggregateCatalog As New AggregateCatalog()

        iAggregateCatalog.Catalogs.Add(New AssemblyCatalog(Assembly.GetExecutingAssembly()))
        iAggregateCatalog.Catalogs.Add(New AssemblyCatalog(GetType(ViewFactory).Assembly))
        iAggregateCatalog.Catalogs.Add(New AssemblyCatalog(GetType(ModelSettingsService).Assembly))
        iAggregateCatalog.Catalogs.Add(New AssemblyCatalog(GetType(ModelSettingsForEarthquakeAfricaIndia).Assembly))
        'iAggregateCatalog.Catalogs.Add(New AssemblyCatalog(GetType(CommonModelSettingsView).Assembly))

        Dim batch As New CompositionBatch()
        batch.AddPart(Me)
        _container = New CompositionContainer(iAggregateCatalog)

        ViewFactory = New ViewFactory(_container)
        _container.ComposeExportedValue(Of ViewFactory)(ViewFactory)
        _container.ComposeParts(ViewFactory)
        _container.Compose(batch)
...
        InitializeComponent()
     End Sub
...
    Private Sub BtnNewRunModelWizard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnNewRunModelWizard.Click
        Dim ExposureDataId As Integer = 12123
        Dim iWindow As Windows.Window = ViewFactory.CreateWindow(Of ModelSettingsView)()
        Dim viewModel As ModelSettingsViewModel = _container.GetExportedValueOrDefault(Of ModelSettingsViewModel)()
        viewModel.ExposureDataId = ExposureDataId
        iWindow.ShowDialog()
    End Sub

namespace Ccp.UI.ModelResults.Views.ModelSettings
{
    [Export(typeof(ModelSettingsViewModel))]
    //[PartCreationPolicy(CreationPolicy.NonShared)]
    public class ModelSettingsViewModel : ViewModelBase
    {
        private int exposureDataId;
        public int ExposureDataId
        {
            get
            {
                return exposureDataId;
            }
            set
            {
                exposureDataId = value;
                RaisePropertyChanged("ExposureDataId");
            }
        }

Next we populate the comboboxs by joining some tables using our POCO EF DAL with Linq then creating an observablecollection from the result

                var result = from av in this.databaseContext.GetAll<CatModel>()
                                 .Where(z => z.PerilId.Value.Equals(selectedModelPeril.PERIL_ID))
                                 .Where(z => ListOfImportedCatModels.Contains(z.Id))
                             join vf in this.databaseContext.GetAll<ModelRegion>()
                             on av.RegionId equals vf.RegionId
                             select vf;

                ModelRegions = new ObservableCollection<ModelRegion>(result);

Here's how joining the Lazy loaded collection of controls (via MEF) with meta data containing an enumeration that has a foriegn key to the corresponding model in our database. This is done within a setter….

                selectedModelRegion = value;
                CatModel Selected = databaseContext
                                    .Query<CatModel>()
                                    .Where(p => p.RegionId == selectedModelRegion.RegionId)
                                    .Where(p => p.PerilId == selectedModelPeril.PERIL_ID)
                                    .FirstOrDefault<CatModel>();

                var result = (from av in this.ModelSettings
                                 .Where(z => (int)z.Metadata.ModelType == Selected.Id)
                             select av).FirstOrDefault();

                SelectedModelSetting = result;

                RaisePropertyChanged("SelectedModelRegion");

Finally here is how we persist data

namespace Ccp.Contracts.Model
{
    public abstract class ModelSettingsBase : NotificationObject
    {
        public string Name
        {
            get { return this.GetType().Name; }
        }

        public abstract void Save(int ModelRunId);
        public abstract bool Validate();
    }
}

namespace Ccp.UI.ModelResults.Views.ModelSettings
{
    [Export(typeof(ModelSettingsViewModel))]
    //[PartCreationPolicy(CreationPolicy.NonShared)]
    public class ModelSettingsViewModel : ViewModelBase
    {
        public RelayCommand<ModelSettingsBase> SaveModelSettingsCommand
        {
            get
            {
                if (saveModelSettingsCommand == null)
                {
                    saveModelSettingsCommand = new RelayCommand<ModelSettingsBase>((ms) =>
                    {
                        // Save
                        int ModelRunId = 123;

                        ms.Save(ModelRunId);
                    }
                    , (ms) =>
                    {
                        // CanSave
                        return ms != null && ms.Validate();
                    });
                }

                return saveModelSettingsCommand;
            }
        }

namespace Ccp.Wpf.Infrastructure.Entities
{
    [CatModelExport(ModelType.EarthquakeAfricaIndia, typeof(ModelSettingsBase))]
    public class ModelSettingsForEarthquakeAfricaIndia : ModelSettingsBase
    {
        public CreditDeductible CreditDeductible { get; set; }
        public ZonalDeductibleByLOB ZonalDeductible3 { get; set; }

        public ModelSettingsForEarthquakeAfricaIndia()
        {
            CreditDeductible = new CreditDeductible();
            ZonalDeductible3 = new ZonalDeductibleByLOB();
        }
        /// <summary>
        /// Dummy implementation
        /// </summary>
        public override void Save(int ModelRunId)
        {
            CreditDeductible.Save(ModelRunId);
            ZonalDeductible3.Save(ModelRunId);
        }

        public override bool Validate()
        {
            return CreditDeductible.Validate() && ZonalDeductible3.Validate();
        }
    }
}

namespace Ccp.Wpf.Infrastructure.Entities
{
    public class CreditDeductible : ModelSettingsBase
    {
        public double Limit { get; set; }
        public double Deductible { get; set; }

        public override void Save(int ModelRunId)
        {
            // Update database here
        }