doque
doque

Reputation: 2733

Merge object #1 to object #2 for all existing properties of object #2

I have a rather verbose object with a lot of properties which I use to transport data to a SQL database. I would now like to provide a "light" version of this object that only uses some properties of the verbose one.

I'm using the light objects to provide through a REST api, and the verbose ones to transport the data, so ideally I could reverse the process as well (overwriting properties of verbose object with existing properties of light object, then save to database).

All these properties will have the same data types, as long as they exist in the light object.

Simple example:

class Verbose {
  public string email;
  public Guid id;
}

class Simple {
  public string email;
  // don't show Guid
}

Now I want to transform all objects of type Verbose to type Simple, ditching all unnecessary properties - is there a simple way to do this?

Ideally this should be reversible as well.

Upvotes: 1

Views: 2162

Answers (3)

Mare Infinitus
Mare Infinitus

Reputation: 8192

You can write a constructor that takes a verbose object and vice versa.

public Verbose(Simple simple)
{
    this.id = Guid.NewGuid();
    this.email = simple.email;
}

public Simple(Verbose verbose)
{
    this.email = verbose.email;
}

That way, you have all the conversion in one place, at least each conversion direction.

This question here might be of interest for you: How to write a converter class? How to efficiently write mapping rules?

EDIT AS IMPORTANT TO OP

Verbose => Simple

If Simple is a subset of Verbose, just derive Verbose from Simple. no conversion needed here.

Verbose IS a Simple then.

Upvotes: 2

Stig
Stig

Reputation: 1323

You can use reflection to traverse objects and reading their property values. In your class add this function

private IEnumerable<PropertyInfo> GetValidInfoes()
{
    foreach (PropertyInfo info in GetType().GetProperties())
    {
         if (info.CanWrite)
            yield return info;
    }
}

Add this loop somewhere where it makes sense to you.

foreach (var item in GetValidInfoes())
{
     var source = myobject.GetType().GetProperty(item.Name);
     if (source != null)
        item.SetValue(this, source.GetValue(item.Name, item.PropertyType), null);
}

Upvotes: 2

Rafal
Rafal

Reputation: 12629

Try AutoMapper. If you will not use flattening it can be reversible.

Upvotes: 1

Related Questions