Last post Jun 24, 2019 06:22 AM by Yuki Tao
Jun 22, 2019 03:23 PM|mahmoud_arafa|LINK
I have a web api request shown below using Postman:
and this is my Custom Validation class which has a line converts 'validationContext' which is supposed to be of type 'customerDto'. The implicit casting to 'Customer' fails and throws an exception. I tried also explicit casting but it doesn't work with 'validationContext'.
How to do casting?
Jun 22, 2019 06:22 PM|PatriceSc|LINK
supposed to be of type 'customerDto'. The implicit casting to 'Customer' fails
More likely you want to cast CustomerDto ?
Edit: if you really declared your class for implicit casting (that is
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/implicit what you shown is explicit casting), I doubt casting from object to Customer could go through an implicit casting though I never tried.
Jun 22, 2019 06:47 PM|DA924|LINK
A class is a blueprint for an object instance, which has public properties, private variables and behaviors/methods that are unique for the object. You cannot cast a object that is defined by one class to be an object that is defined by another class, the
Two casting rules are the following:
1) The cast of the object must be of the same type, which is two objects defined by the same class.
2) .NET will not allow the casting of an object across namespaces even if it's the same object, like trying to cast namespacex.objectxyz to namespacez.objectxyz,
Customerdto should be just a simple object with public properties only with no behavior. Customer I am going to assume is a domain object that has public properties that may have behavior. You are going to have to map the public properties of the DTO to
the public properties of the domain object by doing the mapping manually or using a library like Automapper.
public ProjectViewModels.Project GetProjectById(int id)
var responseDto = _webApi.GetProjByIdApi(id);
var project = new ProjectViewModels.Project
ProjectId = responseDto.ProjectId,
ClientName = responseDto.ClientName,
ProjectName = responseDto.ProjectName,
Technology = responseDto.Technology,
ProjectType = responseDto.ProjectType,
StartDate = responseDto.StartDate,
EndDate = responseDto.EndDate,
Cost = responseDto.Cost
Jun 24, 2019 06:22 AM|Yuki Tao|LINK
Do your error happened on this line?
I suggest you could use the same model,if your want different,you could create a
for example: create a viewmodel named Customer2
Customer2 newcustomer = new Customer2();
newcustomer.Id = customer.Id;
if your fields is too much,I suggest you could use autoMapper to convert,
install autoMapper in Nuget,and then:
Mapper.Initialize(cfg => cfg.CreateMap<Customer, Customer2>());
Customer2 newcustomer= Mapper.Map<Customer2>(model);