Advertisement
otkalce

Entity Framework - mapping

Apr 5th, 2023 (edited)
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.49 KB | Source Code | 0 0
  1. // *** Mapper class (with utility collection-mapping functions) ***
  2.  
  3. public class AudioMapping
  4. {
  5.     public static IEnumerable<BLAudio> MapToBL(IEnumerable<Audio> audios) =>
  6.         audios.Select(x => MapToBL(x));
  7.  
  8.     public static BLAudio MapToBL(Audio audio) =>
  9.         new BLAudio
  10.         {
  11.             Id = audio.Id,
  12.             Title = audio.Title,
  13.             GenreId = audio.GenreId,
  14.             Duration = audio.Duration,
  15.             Url = audio.Url,
  16.         };
  17.  
  18.     public static IEnumerable<Audio> MapToDAL(IEnumerable<BLAudio> blAudios) =>
  19.         blAudios.Select(x => MapToDAL(x));
  20.  
  21.     public static Audio MapToDAL(BLAudio audio) =>
  22.         new Audio
  23.         {
  24.             Id = audio.Id ?? 0,
  25.             Title = audio.Title,
  26.             GenreId = audio.GenreId,
  27.             Duration = audio.Duration,
  28.             Url = audio.Url,
  29.         };
  30. }
  31.  
  32. // *** POST action that uses Mapper class ***
  33.  
  34. [HttpPost()]
  35. public ActionResult<Audio> Post(BLAudio audio)
  36. {
  37.     try
  38.     {
  39.         if (!ModelState.IsValid)
  40.             return BadRequest(ModelState);
  41.  
  42.         var dbAudio = AudioMapping.MapToDAL(audio);
  43.  
  44.         _dbContext.Audios.Add(dbAudio);
  45.  
  46.         _dbContext.SaveChanges();
  47.  
  48.         audio = AudioMapping.MapToBL(dbAudio);
  49.  
  50.         return Ok(audio);
  51.     }
  52.     catch (Exception ex)
  53.     {
  54.         return StatusCode(
  55.             StatusCodes.Status500InternalServerError,
  56.             "There has been a problem while fetching the data you requested");
  57.     }
  58. }
  59.  
Tags: ef-mapping
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement