简体   繁体   中英

Mapping two classes in c#

I have two classes

public class foo1
{
  public int id;
  public string image_link;
  public string sale_price;
}

and

public class foo2
{
 public int Id;
 public string ImageLink;
 public string SalePrice
}

The property values differ only by underscore and cases. I need to map these two classes.

For now I am trying something like this and its working:

//var b = object of foo2
var a = new foo1{
 a.id = b.Id,
 a.image_link = b.ImageLink,
 a.sale_price = b.SalePrice
}

I heard of AutoMapper, but I din't have clear idea of how i am going to use that or where is the option of ignoring cases or underscores in it. or is there any better solution to it?

Your code is fine and works as expected.

I would personally advise you to not use automapper. There are plenty explanations about why on the Internet, here's for example one: http://www.uglybugger.org/software/post/friends_dont_let_friends_use_automapper

Basically the major issue is that your code will silently fail at runtime if you rename some property on your foo1 object without modifying your foo2 object.

As @ken2k answer, I suggest you to don't use an object mapper.

If you want to save code you can just create a new method (or directly in the constructor) for the mapping.

public class foo1
{
  public int id;
  public string image_link;
  public string sale_price;

  public void map(foo2 obj)
  {
    this.id = obj.Id;
    this.image_link = obj.ImageLink;
    this.sale_price = obj.SalePrice;
  }
}

Then

//var b = object of foo2
var a = new foo1();
a.map(b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM