Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Initialize T type c#

I Have a BaseController.

 public abstract class BaseController<TEntity, TNewDTO, TEditDTO> : Controller, ICrudController<TNewDTO, TEditDTO>
        where TEntity : class
        where TNewDTO : new()
        where TEditDTO : new()
    {
    public virtual ActionResult Edit(int? Id)
    {
        if (Id == null) return new HttpStatusCodeResult(400);
        var ent = _db.Set<TEntity>().Find(Id);
        if (ent == null) return new HttpStatusCodeResult(404);

        var editDTO = new TEditDTO();

        editDTO = ent; // how initilze?


        return View(editDTO);

    }
}

in Edit Action, check validation, find entity from context and fill Edit data Transfer Object (DTO) EditDTO and ent have some properties. how can i initialize automatically one T with another t type with properties with same name and type

like image 768
Mohammadreza Avatar asked Feb 03 '26 13:02

Mohammadreza


1 Answers

I would suggest AutoMapper

AutoMapper is a simple little library built to solve a deceptively complex problem - getting rid of code that mapped one object to another. This type of code is rather dreary and boring to write, so why not invent a tool to do it for us?

like image 162
Eric J. Avatar answered Feb 05 '26 06:02

Eric J.