Reputation: 3447
So I have an EF4 class called Contact, that has the basic fields such as ID, Name, Surname etc.
Now I want to create another 2 classes called SelectedUser and LoggedUser that basically inherit from the Contact class, however they have additional methods.
So I created a class called SelectedContact as follows :-
public partial class SelectedContact : Contact
{
methods..........
}
I have a problem though, for example I want to retreive a SelectedContact. So basically what I am doing is
Contact contact = db.Contacts.FirstOrDefault(u => u.id_contact == contactId);
SelectedContact selContact = (SelectedContact)contact;
This does not work, telling me that I cannot cast from Contact to SelectedContact.
I also tried
Contact contact = db.Contacts.FirstOrDefault(u => u.id_contact == contactId);
SelectedContact selContact = contact as SelectedContact;
but this returns a null selContact.
I know that I can move the fields one by one, ie :-
SelectedContact selContact = new SelectedContact();
selContact.id_contact = contact.id_contact;
however I am sure that there is a better way to do that.
Any help is very much appreciated!
Thanks a lot for your help and time.
Upvotes: 1
Views: 55
Reputation: 364279
You cannot cast instance retrieved from database to SelectedContact
because it is not SelectedContact
. It is only Contact
and casting is not possible without creating the new instance (you will have to override cast operator).
The reason is that your Entity model doesn't contain your derived classes and because of that every time you query the database you get only Contact
instance. To support your scenario you will have to map your derived classes as well but it has multiple disadvantages. For example you cannot change the type of the contact.
Upvotes: 1