logo
down
shadow

Proper way to create domain models and viewmodels in microservices


Proper way to create domain models and viewmodels in microservices

Content Index :

Proper way to create domain models and viewmodels in microservices
Tag : chash , By : Janko
Date : November 29 2020, 04:01 AM

help you fix your problem I am going to assume that you are using a Web Api but the same principles apply to an MVC app. I normally have a mapper layer that takes a domain object and maps it to a view model or dto. This way you can reuse the mapper anytime you want to return the same view model. So if you make a change to the view model it is all located in one place.
See code below to answer question 1.
//Fake view model
public class CalendarEventViewModel
{
    public int EventId { get; set; }

    public string Title { get; set; }

    public DateTime? StartDateTimeUtc { get; set; }

    public DateTime? EndDateTimeUtc { get; set; }

    public string Summary { get; set; }

    public bool IsApproved { get; set; }

    public string TimeZoneId { get; set; }
}


public interface IMapper<in TIn, out TOut>
{
        TOut Map(TIn model);
}

public class CalendarEventViewModelMapper : IMapper<CalendarEvent, CalendarEventViewModel>
{
    public CalendarEventViewModel Map(CalendarEvent model)
    {
        return new CalendarEventViewModel
        {
            EndDateTimeUtc = model.EndDateTimeUtc,
            EventId = model.EventId,
            IsApproved = model.IsApproved,
            StartDateTimeUtc = model.StartDateTimeUtc,
            Summary = model.Summary,
            TimeZoneId = model.TimeZoneId,
            Title = model.Title
        };
    }
}

[Route("api/Values")]
public class ValuesController 
{ 
       public ValuesController( IMapper<CalendarEvent, CalendarEventViewModel> calendarMapper)
       {
           _calendarMapper = calendarMapper;
       }

        // GET api/values/5
        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {

            var calendarEvent = GetMyCalendarEventFromDB(id);

            return this.Ok(_calendarMapper.Map(calendarEvent));
        }

        private CalendarEvent GetMyCalendarEventFromDB(int id)
        {
            return new CalendarEvent("yyyy-dd-MM")
            {
                EndDateTimeUtc = DateTime.UtcNow.AddHours(3),
                EventId = id,
                IsApproved = true,
                StartDateTimeUtc = DateTime.UtcNow.AddHours(2),
                Summary = "My magical Event",
                TimeZoneId = "UTC",
                Title = "Magical Event"
            };
        }
    }
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Design patterns advice - separating ViewModels from domain models


Tag : chash , By : Christopher
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I also don't see much of a reason to keep the DAL separate from the MVC layer. In case you're interested, here is the layout that I've used for multiple project and I find it is very usable and flexible.
DataObjects Basic objects with only properties. Also includes enumerations which the DataObjects use.

Easily create MVC ViewModels from Entity models?


Tag : chash , By : Joe Sweeney
Date : March 29 2020, 07:55 AM
This might help you You could consider using T4 templating, see this MSDN magazine article to get started. You could create a template that uses reflection to get the properties of your Model, and generate ViewModel from this.

AutoMapper: two-way, deep mapping, between domain models and viewmodels


Tag : chash , By : moss
Date : March 29 2020, 07:55 AM
it should still fix some issue In the end I found AutoMapper was unsuited to my scenario.
Instead I built a custom utility to provide bidirectional mapping & deep property mapping allowing configuration as follows. Given the scope of our project I believe this is justified.
BiMapper.CreateProfile<Client, ClientNotificationsViewModel>()
    .Map(x => x.NotificationSettings.ReceiveActivityEmail, x => x.ReceiveActivityEmail)
    .Map(x => x.NotificationSettings.ReceiveActivitySms, x => x.ReceiveActivitySms)
    .Map(x => x.ContactDetails.Email, x => x.Email)
    .Map(x => x.ContactDetails.MobileNumber, x => x.MobileNumber);

BiMapper.PerformMap(client, viewModel);
BiMapper.PerformMap(viewModel, client);

MVC map Viewmodels to domain models


Tag : chash , By : Thomas Gueze
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I am struggling to figure out how to map my viewModels to domain models for to the Index, Edit, Details and Delete Action Result in the controller. , To map your domain model to the view model in the edit method
Parent p = db.Parents.Find(id);

ParentsEditVM model = new ParentsEditVM()
{
  ParentID = p.ParentID,
  FirstName =p.FirstName,
  LastName = p.LastName,
  Children = p.Childs.Select(c => new ChildVM()
  {
    ChildID = c.ChildID,
    Name = c.Name,
    ... etc
  }).ToList(),
};
....
return View(model);

In Asp.net MVC, is it advisable for viewmodels to derive from domain models?


Tag : chash , By : taviso
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • c# wpf | create complex object with user-defined name to Serialize into JSON
  • How can I get a instance of a generic list with reflection?
  • WPF XAML - Design time and visibility of textbox
  • EF Core and MySql query is too slow
  • Getting Registered App Display Name from an App Id
  • How to get all variables from a string
  • Delete entity with all childs connected
  • Azure Build agent cant´t find class library referance
  • Initialize Nested Dictionaries in c#
  • .Net Core Binding
  • Generic event test method, preventing code duplication
  • How do I keep the ellipses in the center when the screen is resized
  • How to require a property using JsonSchema.NET?
  • C# XDocument Element/Elements returns null
  • Autofac keyed service with IEnumerable relationship type
  • Installing EntityFramework via NuGet manager
  • Always Check if there is Internet Connection Xamarin forms
  • WCF OneWay service slows down when aspNetCompatibilityEnabled is set to false
  • Can we use JsonRequestBehavior.AllowGet with [HttpPost] attribute?
  • How to customize the Setup wizard with custom forms in Visual Studio setup project
  • C# ASP.NET - Use method from another class to create labels
  • C# List IList or IEnumerable as argument
  • Parsing File with C# And Replace method
  • Losing special unicode characters in encryption (C#)
  • Getting stored procedure returned value instead of row affected
  • How can I construct HTML using NameValuePair in android?
  • Loading a pop up page in ASP.net through a js file
  • How to pass alert or notification message from controller to View?
  • C# to pause, turn on ssas server, backup cube.... how to?
  • How to execute DataTable.Select() for a column of custom class type for a particular element in that C#
  • how to connect mysql8.0 with C#
  • Passing incorrect values into MultiValueConverter by MultiBinding
  • Can i use IEnumerator as Update func?
  • How to convert API Json response to C# Array?
  • Blazor Textfield Oninput User Typing Delay
  • Performing both layout and render transform results in wrong output
  • uwp beforetextchanged cursor moving in front of text
  • How to keep duplicates from a string[] exclude words from a List and print them out
  • .Net Core Strings.Asc/Mid/Chr/Len missing even after importing Microsoft.VisualBasic
  • How to return to previous search page without being asked to Confirm Form Re-submission and keeping the results on ASP.N
  • How set a identity scaffolding item/page how initial page in asp.net MVC core?
  • LINQ isn't calling Dispose on my IEnumerator when using Union and Select, expected behavior or bug?
  • What is "ByteArray.uncompress()" in AS3 equivalent to in C#?
  • Getting a specific letter from a string variable for my simple guessing game for clues
  • Send an email with Outlook without a subject --- dialog box issue
  • passing List<MyModel> from my controller in the "WebInterfaceProject" to the processor method in "D
  • How to convert Word document created from template by OpenXML into MemoryStream?
  • How can I make a single slider that changes the color of an object?
  • Remap JSON parameter in c#
  • What is the difference between "this ref" and "ref this" when talking about C# 7.2 ref extension met
  • Convert OpenSSL encryption into native C#
  • Accessing Properties in Razor Pages
  • How to get SOAP element value
  • Projection after Group
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com