0

I want my model to accept all 3 different types of value in id(basically Guid and int only)

This is my model-

public class Base
    {
        public dynamic Id { get; set; }
        public string Type { get; set; }
    }

This is my json-

{
                "id": "31367556-cda7-4fce-9d8a-2cd6f46544f9",
                "type": "form"
},

{
                "id": "123",
                "type": "form"
},

{
                "id": 456,
                "type": "form"
}

1 Answers1

0

First of all you need to answer on the following questions: why you really need dynamic type? How are you going to use it?. After that you can choose approach to implement. Maybe you need just string.

Another approach, is to use to 2 properties and for example enum which indicate for you which id should be selected.

Make your Data model which accept string

public class Base
    {
        public string Id { get; set; }
        public string Type { get; set; }
    }

And after you received and parse it you need to map this Data Transfer Model to Model and use it in your Application only Model types.

Mapping can be

//your ApplicationModel
public class BaseModel
{
  public Guid GuidId{get;set;}
  public int Id{get;set;}
  public IdType{get;set;}

  public enum IdType
  {
     Guid,
     Int
  }
}

public BaseModel Map(Base dto)
{
  var model=new BaseModel{Type= dto.Type};
  var guidResult = Guid.TryParse(dto.Id,out model.GuidId);
  if(!guidResult) int.TryParse(dto.Id, out model.Id);
  model.IdType = guidResult?IdType.Guid:IdType.Int;
  return model
}

using dynamic type for me is Bad practice. I know only few cases where it acceptable. More info you can find here:Is the use of dynamic considered a bad practice?

Yauhen Sampir
  • 1,989
  • 15
  • 16