I have a Data layer and Business layer in my App.
In data layer I have imported database tables as objects using entity framework.
One of them is Unit table for example.
Now in business layer I want to add some methods to Unit of data layer so I have this class:
namespace Business.Entity
{
public class Unit : Data.Unit
{
//Some business affairs here
}
}
And for loading units in UI I have created a repository in business layer :
public static IEnumerable<Data.Unit> LoadUnits()
{
return from entity in StaticDataContext.Units select entity;
}
Everything is good till now.
But I want to load a list of Business.Unit in UI so I wrote this one:
public static IEnumerable<Business.Entity.Unit> LoadUnits()
{
var result = (from entity in StaticDataContext.Units
select entity).ToList().Cast<Business.Entity.Unit>();
return result;
}
It compiles well but then I get this runtime error when binding it to a Grid:
InvalidCastException: Unable to cast object of type 'Data.Unit' to type 'Business.Entity.Unit'
Can any one say how to arrange the classes to be able to load business classes in UI ?
Thanks
You can not directly cast parent object to child object. Possible solutions for your problem:
Create in
Business.Entity.Unitclass a constructor acceptingData.Unitas argument and assigning all necessary properties, like:After that you can do:
Rewrite your
Business.Entity.Unitclass so that it does not inheritData.Unit, but acceptsData.Unitentity as a constructor parameter, aggregates it (stores in a local private member) and presents wrapper properties and functions to operate on itRemove your
Business.Entity.Unitclass entirely and implement all additional methods as extension methods.I’d vote for the third one because IMHO it leaves code a bit cleaner and does not have overhead of introducing and managing additional entity.