Avoid explicitly marking a property as not modified in Entity Framework - c#

Whenever I update an entity, I need to include every field in the form as a hidden input, so that it's value doesn't get set to null.
Setting the property as not modified, like the code below, prevent this. But this code is abstracted into a generic IRepository interface encapsulated by an UnitOfWork class, so I can't specify non-modified properties for each entity.
Entry(entry.Entity as MyModel).Property(e => e.AProperty).IsModified = false;
Is there another way to do that?

You could use a MVVM architectural pattern. The Model View ViewModel (MVVM) is an architectural pattern used in software engineering originated from Microsoft as a specialization of the Presentation Model design pattern introduced by Martin Fowler.
Model : Model refers to your application data. In a real world ASP.NET web application, your data will typically be stored in a SQL Server database and your UI gets it from the server by making AJAX requests or some similar technique.
View Model : View Model refers to your data and UI level operations that you wish to perform on the data. The operations may include business validations or conditional checks or updating certain parts of the web page. You can think of View Model as a wrapper over your model data that adds UI level operations to it.
View : View is the user interface of your application. A View interacts with View Model to invoke some operations. A View is updated whenever data from the View Model changes. For a web application a view typically takes the form of an HTML document.
Here is a real world example using ASP.NET and EF. http://blog.tonysneed.com/2014/05/28/real-world-mvvm-with-entity-framework-and-asp-net-web-api/

Related

ASP.NET Core specific way to reuse Edit and New view content in cshtml

I have a New and Edit view that basically contain duplicate cshtml. What's the most efficient way to refactor so I can stay DRY?
I already looked through Stack Overflow, and all the answers I could find were for .NET Framework. I wanted to see if there are more efficient ways to reuse code now, with ASP.NET Core.
Is using a Partial View or a View Component the most efficient method? Or is there another ASP.NET Core specific way to handle this?
Partial Views and View Components both allow you to centralize your views, and in that regard are interchangeable. Partial Views, however, exclusively contain view information (i.e., a cshtml file). By contrast, View Components additionally allow you to define preprocessing logic (similar to an [HttpGet] controller action).
Data Access and Parameterization
It's important to note that both Partial Views and View Components can have arguments or values passed into them.
In a Partial View, this is done by relaying either a ViewDataDictionary or a custom view model to the Partial View (reference); this can be done using either the PartialAsync() HTML Helper or by using the <partial /> tag helper's model or view-data attributes.
In a View Component, this is done by defining parameters on the InvokeAsync() method, and then relaying those as either an anonymous object via the InvokeAsync() HTML Helper or as attributes on the <vc:[view-component-name] /> tag helper.
As a result, both approaches can be parameterized and/or data bound, thus allowing them to be respond to the current state.
View Component Specific Capabilities
Where View Components distinguishes themselves is in that ability to define preprocessing logic via the InvokeAsync() method before returning a view model to the view, potentially including access to classes registered via dependency injection (e.g., via a composition root or a dependency injection container).
This is especially useful if your view needs to access data that's not (conveniently) available in the parent view—e.g., via a dependency, a database, or a webservice. So, for instance, if your view component is used by dozens of different views, but always needs access to similar data, this can allow you to centralize that logic so you don't need to look it up in each controller.
Examples: Given the ability to lookup data as part of a view component, I frequently use them for site navigation. That way, I don't need to lookup the navigation data in every single [HttpGet] action, nor include it in every single view model; it can be self-contained. Similarly, I use it for views containing common lookup data, such as dropdown boxes bound to data retrieved from an API or database call.
The Most Efficient Method
As far as which is most "efficient", that is a fairly subjective question, and not one we can answer without more information about your use case.
If a Partial View satisfies your needs, however, it is certainly the simplest and easiest approach: A View Component necessitates that an additional class be created and registered in order to support your view.
The question here, though, is likely less about efficiency and more about your requirements. If your view needs additional preprocessing to e.g. modify the view data, construct a new view model, or collect additional data, then you should use a View Component; otherwise, prefer a Partial View.
That said, given that you're looking to centralize the markup between a New and Edit view, I would expect a Partial View to satisfy your requirement. Both views will likely share an existing view and binding model, and the data populated will be specific to each view, therefore there likely isn't much need to centralize any pre-processing logic.
The one potential exception is if your New and Edit forms include lookup data—such as dropdown lists—sourced from a database. That said, as these views are almost certainly being returned from the same controller, you can easily centralize the lookup of that data in the controller itself, without needing to rely on a View Component to do that for you.
The best way to go about it is to use partial views!
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-6.0

Separation of Concerns in MVVM

I am working on understanding MVVM better, and from trusty Wikipedia (and lots of other research), I have gathered that the ViewModel holds presentation logic and the Model holds the business logic.
MVVM Pattern (Image courtersy of Wikipedia)
My question is, how is there a separation of concerns between logic and data when the Model is holding the business logic? Why is this a good pattern and why would I want to use it instead of using MVC where the Controller handles business and presentation logic (if I understand it correctly)? (I am using WPF, which based on my research, mainly uses MVVM and rarely uses MVC, and I still don't understand why).
Separating presentation logic from business logic allows you to change business logic without directly affecting presentation logic.
For example, if you have a RESTful web API that retrieves some data a view should render, the ViewModel should not be directly handling the HTTP operation or any translation of the incoming data. The ViewModel should ask a (separated) service class to retrieve that data and then the ViewModel can choose how to present that data, such as by pagination, sorting, filtering, and so on. You may choose to paginate at the web API level instead, but that's an implementation detail. In the event that your API contract changes, you can change the web API service without affecting the presentation logic: separation of concerns.
Let's get some things straight:
MVC = Model View Controller
MVVM = Model View ViewModel
With MVC, the controller controls the data and the business logic, the model stores the data temporarily, and the View can read the data from the model. In this model, the View handles the presentation logic. In C#, you can use Razor Pages (.cshtml) to dynamically insert values into the view.
MVVM is very similar. The Model is responsible for holding the data and business logic, the View Model holds the data temporarily, and the View controls the presentation logic. The main difference is the physical separation in your code.
With MVC, each step is separated into its own file. With MVVM, usually two or more steps are combined together into one file. This can be advantageous because it keeps you from having controllers that are hundreds or thousands of lines long if you have lots of pages. I personally still like MVC, because it keeps everything separate instead of combining it together.

What is the role of Controller in MVC model?

I have gone through some answers here and and some articles on MVC but I still have a confusion regarding the role of a Controller in a MVC application.
I read in a book that the Model is self-contained and functions independent of View and Controller. And that the Model contains the business logic and data access codes. Source
Also in the best answer
here
What goes into the "Controller" in "MVC"?
But the other answers around here say that it is the Controller that represent the business logic
Where can I find a dead-simple explanation of MVC?
So which is the correct answer?
Wikipedia states very simply: The controller, accepts input and converts it to commands for the model or view.
https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
This answer is correct
Model: This component represents the data and the business logic of the application.The model in the MVC framework is not related to the presentation of the application.The model component focus on keeping track of the state of the application.It also defines business rules for data, means how the data can be changed and manipulated.
View: The view provides the user interface (UI) for the model. The main work (function) of the view represents the information in user understandable format. It uses UI Components such as HTML,CSS,Jquery etc.
Controller: Controller act as a mediator between view and model. it is responsible to control the data transmission between the model and the view. It maps the user action into model updates.The controller layer is helpful to select the most appropriate view and delivers it to the user.
Actually, The Controllers are mediater between the view and model. they don't define the business logic. Models are responsible for business logic.
Controller acts as a mediator between the View and the Model class. It is used just to remove the dependency between model and view classes.
Kindly refer to this link..
https://www.tutorialspoint.com/mvc_framework/mvc_framework_controllers.html
The ASP.NET MVC framework maps URLs to classes that are referred to as controllers. Controllers process incoming requests, handle user input and interactions, and execute appropriate application logic. A controller class typically calls a separate view component to generate the HTML markup for the request.
The Controller class is responsible for the following processing stages:
Locating the appropriate action method to call and validating that it
can be called.
Getting the values to use as the action method's arguments.
Handling all errors that might occur during the execution of the action method.
Providing the default WebFormViewEngine class for rendering ASP.NET page types (views).

Are all MVC models lightweight?

So I was first introduced to the idea of a model when I learned WPF. The MVVM concept of a model seems to be more aligned to general 'business logic' encased in a class/set of classes. When I look at MVC though, the model seems to be lightweight-classes that are "passed" to and from the user via forms. Is this assessment correct, or are there situations where a model is something heavier (does more than just hold and validate data input from the user).
You can use Models (classes) as data container (which i usually do) , look at anemic domain model (http://en.wikipedia.org/wiki/Anemic_domain_model), then you can implement business layer, service, data layer independently.
Or you can implement them within your model, which some folks wants to do that due to encapsulation, and several design priciples.
Look into domain driven design as well. (http://en.wikipedia.org/wiki/Domain-driven_design)
Well in MVC or another similar Design Pattern you have defined 3 separate layers of your application. The model with the logic of your objects, the view for showing and getting information from the user, and then a controller witch does the interaction and exchanges between the 2.
MVC is more used for web apps and MVVM with WPF. The reason is that you with WPF can do the databinding of the objects in your View with the one in the ViewModel.
For example a Twiter app: You can do have a model (tweetItem) with all the properties of a Tweet, a ViewModel that gets and stores the tweets in an collection and view that has a list, for showing them, binded to that collection.
There for MVVM or MVC only impact in your app is on how the code is organized.

What are my controller in my application with a MVVM design pattern

I have developed a WPF-application. I have a mainwindow which inherit from Window, a tabcontrol and many tabitems in this tabcontrol which inherit from UserControl. Every tabitem has its own cs-file, where I code in C# all the businesslogic, and a XAML-file where the development of the UI is done. I also have a SQL Server with a database which i connect to trough LINQ.
So i have to write about my choice of which controller i use in my application. This is where i get confused, since i havent manually programmed a controller and i thought the ViewModel would behave like a controller in my case. Could this be correct? Can the ViewModel behave like a controller?
A controller can send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document). It can also send commands to the model to update the model's state (e.g., editing a document). Model_View_Controller
The viewmodel is a “model of the view” meaning it is an abstraction of the view that also serves in mediating between the view and the model which is the target of the view data bindings. It could be seen as a specialized aspect of what would be a controller (in the MVC pattern) that acts as a converter that changes model information into view information and passes commands from the view into the model. The view model exposes public properties, commands, and abstractions. Model_View_ViewModel
The introduction of MVVMC (MVC + MVVM) is nessesary in cases you would like to drive many similar pairs of View-ViewModel (use cases). You can then introduce controllers. Model_View_ViewModel_Controller
In the simplest case, have the ViewModel implement the "controller" logic. For large applications, I sometimes use an MVVMC pattern which uses a separate controller class. There has been a lot of recent support on the blogosphere for using MVVMC over MVVM.
MVVM is dead, long live MVVMC!
MVMMC – MVVM grows a Controller

Categories

Resources