0

I have two tables "Product" and "Product_Recovery". They have identical structure.

So, I would like to Cast Product Entity Object to Product_Recovery object and vice versa, but I am getting an error:

cannot convert from 'MyProject.Objects.Product' to 'MyProject.Objects.Product_Recovery'

Is there any easy way to do this?

3
  • Possible duplicate of Cast between interfaces whose interface signatures are same Commented Jun 10, 2016 at 3:24
  • @Aron: Yes, this is a duplicate, but that question is 4 years old and AutoMapper may not have been available then. Honestly not sure if the best practice is to leave or close in the case where the referenced question is dated Commented Jun 10, 2016 at 3:30
  • @caesay Normally I would say that you should 1) vote to close this question 2) Answer THAT question with your modern answer. However, the top answer there is a Jon Skeet answer, which complicates things....I'm sure there is a meta for this. Commented Jun 10, 2016 at 3:50

1 Answer 1

4

No, you can't just cast one object to another unless one derives from the other. How is C# supposed to know that the classes are the same? You can however make the transition from Product to Product_Recovery by using the AutoMapper library, which makes this easier by the use of Reflection.

Check out the Project Page or Getting Started, and install from Nuget when you're ready to use it.

The simplest example of how to use would be (copied from Getting Started):

// execute this somewhere in your program construction 
// only once to generate the required mappings
Mapper.Initialize(cfg => cfg.CreateMap<Product, Product_Recovery>());

// execute this to transform from one to another:
Product dto = Mapper.Map<Product_Recovery>(productInstance);
Sign up to request clarification or add additional context in comments.

1 Comment

Feel free to add .ReverseMap() at the end if you need it both ways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.