MB34
MB34

Reputation: 4424

Adding new property to .Net object

I have a WCF web service that is consumed in an MVC4 application that returns an object. I want to add another property to the object after it is loaded. Essentially I want a clone of the object plus my new property.

How would I do that?

Would it be best to deserialize to JSON, then add the new property and then serialize it into my new object with the extra property or is there another way to do it?

Upvotes: 2

Views: 2274

Answers (3)

rnort
rnort

Reputation: 107

Would it be best to deserialize to JSON, then add the new property and then serialize it into my new object with the extra property or is there another way to do it?

It's definitely would be easier and cost less efforts to use JSON.

But if you want more control over the generation process see that answer how to generate classes on the fly.

Upvotes: 0

Reza Aghaei
Reza Aghaei

Reputation: 125227

If you want to keep things simple, you can simply create your new Type including all properties of given object and your desired new property, then fill your new class and do what do you want with it.

Also consider reading Note part.

For complicated cases and large applications, you can consider solutions like what abatishchev mentioned in his answer.

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


class FooViewModel
{
    public FooViewModel()
    {
    }

    public FooViewModel(Foo foo)
    {
        this.Id= foo.Id;
        this.Name= foo.Name;
    }

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

    public string NewProperty{ get; set; }
}

And use it this way:

var foo = Service.GetFoo();
var fooViewModel= new FooViewModel(foo);
fooViewModel.NewProperty = "new value";

Note:

  • You can use a Foo instance in FooViewModel and all getters and setters act on that instance to keep thing synchronized.
  • Sometimes you can enhance the solution using inheritance from Foo, this way you don't need too create each properties again.
  • For complicated cases and large applications, you can consider solutions like what abatishchev mentioned in his answer.

Upvotes: 4

abatishchev
abatishchev

Reputation: 100288

I think what you're looking for is AutoMapper. You can map one object into another. Say, you have a DTO entity with X properties. Then you have a business logic entity with the same X properties + Y additional. AutoMapper will handle it easily.

class OrderDto
{
    public int OrderId { get; set; }
}

class OrderViewModel
{
    public int OrderId { get; set; }

    public int DisplayOrder { get; set; }
}

Mapping:

var dto = new OrderDto { OrderId = 2 };
var vm = mapper.Map<OrderViewModel>(dto);
vm.DisplayOrder = 3;

Upvotes: 3

Related Questions