Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert one object to another in C#

Tags:

c#

.net-core

I am new in C#, dotnet core. I am getting data from database like below. This data is very flat. I need to convert to another object.

public class Lead
    {
        public long Id { get; set; }

        public short LeadCreatorId { get; set; }

        public short LeadOwnerId { get; set; }

        public string ProductId { get; set; }

        public LeadPriority Priority { get; set; }

        public LeadStatus Status { get; set; }

        public long LeadCustomerId { get; set; }  

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string EmailAddress { get; set; }

        public string MobileNo { get; set; }

        public DateTime CreatedOn { get; set; }
    }

I need to convert it to below object.

public class LeadDto
    {
        public long Id { get; set; }

        public short LeadCreatorId { get; set; }

        public short LeadOwnerId { get; set; }

        public string ProductId { get; set; }

        public LeadPriority Priority { get; set; }

        public LeadStatus Status { get; set; }

        public LeadCustomer LeadCustomer { get; set; }

        public DateTime CreatedOn { get; set; }
    }

Where LeadCustomer is like below -

public class LeadCustomer{

            public long Id { get; set; }

            public string FirstName { get; set; }

            public string LastName { get; set; }

            public string EmailAddress { get; set; }

            public string MobileNo { get; set; }
}

How can I easily do that? Can I use dto for the conversion.

like image 985
toothful Avatar asked Nov 30 '25 04:11

toothful


1 Answers

They are many many mapper libraries out in the internet. To name a few

  • automapper
  • mapster
  • emitmapper

All of them have their own pros and cons. I would personally feel writing your own mapper methods would be worth it as you will have complete control of what you write.

I agree it could take some time but it doesn't take so long.

like image 106
G_S Avatar answered Dec 02 '25 18:12

G_S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!