Bind a complex type property to a primary type

Viewed 47

Suppose I have a ViewModel in .net core client,

public class MyViewModel{
   ...
   public List<MyClass> NamesList{get;set;}
   ...
}

where MyClass is defined as below,

public class MyClass{
   public int Id{get;set;}
   public string Name{get;set;}
}

Now if my api endpoint(POST request) expects a model as below,

public class MyApiModel{
   ...
   public List<string> NamesList{get;set;}
   ...
}

how to bind List<MyClass> to List<string> by using Name property of MyClass

Note - 1) Using duplicate property in client or api would not be a good solution I feel 2) Using a different ViewModel with List<string> as a property type and copy the fields before POSTing to api is also not suitable in this case because if the request fails, I would require the old model to pass it to the view with model errors

1 Answers

If you need different data structures, you'll need different classes. This is quite common. So the question seems to be more about how to map structure A to structure B.

There are multiple options:

For DTOs (like your api model class) I'd take a look at C# records https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/records which are perfect for such dtos.

 public record MyApiModel(List<string> Names)
 {
     public static MyApiModel From(Model model) 
         => return new(model.NamesList.Select(n => n.Name));
 }

One nice effect of using the constructor to set all data is, that the compiler will show you all places that needs to be updated if you modify your models.

Related