Tuesday, July 31, 2018

Use of Linq when mapping between objects

The class which data is loaded from the database. Notice data is loaded through Entity Framework

    public class UserType : EntityBase
    {
        [DisplayName("User Type")]
        [Required]
        [Remote("IsUserTypeExist", "Validation", ErrorMessage = "user type already exist! ")]
        public string UserTypeName { get; set; }

        public virtual List<User> users { get; set; }
    }

The Data Transfer Object which is used in the system

    public class UserTypeDTO
    {
        public int Id { get; set; }
        public string UserTypeName { get; set; }
        public bool Archived { get; set; }
    }

Mapping inside the method

        public List<UserTypeDTO> GetUserTypes(AppContext db)
        {
            return db.UserTypes.Select(u => new UserTypeDTO()
            {
                Id = u.Id,
                UserTypeName = u.UserTypeName,
                Archived = u.Archived
            }
            ).ToList();
        }