I have a class Employee, and FulltimeEmployee and ParttimeEmployee classes derived from it. I apply a [KnownType] attribute on the Employee class. The Employee class is used as a DataContract for a WCF Service.
I have an MVC application as a WCF client. I successfully retrieve either FulltimeEmployee or ParttimeEmployee as needed, and use it as a model for the view. The model is of a base type Employee. The hierarchy is preserved:
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "0.5.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="FullTimeEmployee", Namespace="http://schemas.datacontract.org/2004/07/EmployeeService")]
public partial class FullTimeEmployee : EmployeeService.Employee
{
...
But when I try to save a new employee, I get an exception:
InvalidCastException: Unable to cast object of type 'EmployeeService.Employee' to type 'EmployeeService.PartTimeEmployee'.
Here is the code:
Employee emp = null;
if(employee.Type == EmployeeType.FullTimeEmployee)
{
...
}
else
{
emp = new PartTimeEmployee
{
Name = employee.Name,
Gender = employee.Gender,
Type = employee.Type,
DateOfBirth = employee.DateOfBirth,
HourlyPay = ((PartTimeEmployee)employee).HourlyPay,
HoursWorked = ((PartTimeEmployee)employee).HoursWorked
};
Why does this happen?