Im working with ASP.NET WebAPI & EntityFramework.
I noticed that I could create API controller with VS template based one of my entities. The controller automatically has methods PUT, GET, POST, DELETE.
Its very usefull and makes life easier.
But, the db connection initial in every single controller, I mean, every controller has DB connection object.
(for example: ExampleEntities db = new ExampleEntities())
Is that the right way to work?
Or should I create a BL or something to wrap the DB, and the controllers will access the db via BL?
tnx!
You can use UOF + Repository + IoC architecture.
Related
About 900 thousand database records are used by some calculation,so I want to fill a datatable when webapi startup ,and the datatable can be used by some controller and method.
What's the proper way?
About 900 thousand database records are used by some calculation,so I want to fill a datatable when webapi startup ,and the datatable can be used by some controller and method.
If the database query and calculation would take long time to complete, you can try to implement a hosted service with background task logic, and cache caculation result in redis etc. Then you can get cached data from redis within your controller and method.
Besides, if query and calculation logic would be not very complex, you can try to create and implement a custom service for querying database and doing calculation, and register your service then use it within your controller.
I'm trying to understand how I should use the MVVM pattern for a CRUD operation. Currently I have methods in my API controller such as below. My question is: using MVVM pattern, should I still build my api like that (e.g., accessing DB)? Or should it be changed? If nothing changes, in which case I would implement ViewModels and how they should be managed by the API? I made some researches but it's still not clear for me.
public IHttpActionResult GetProduct(int id)
{
var product = _context.Products.SingleOrDefault(p => p.Id == id);
return Ok(product);
}
[HttpPost]
public IHttpActionResult CreateProduct(Product product)
{
...
_context.Products.Add(product);
_context.SaveChanges();
return Created(new Uri(Request.RequestUri + "/" + product.Id), product);
}
I think part of the problem is that you don't understand the role of MVVM in a web application. To understand, you have to look at a web application as composed of two separate applications--the server side, and the client side.
Server side, the pattern being used is MVC (not surprising, it's called ASP.NET MVC for a reason). If you're trying to fit your understanding of MVVM around the MVC pattern--don't. It doesn't apply. The MVC pattern on the server is simple to understand and implement; don't try to crowbar any MVVM into it. Just design your server side code using the server side pattern.
Client side is a different matter. By default, ASP.NET MVC using Razor pages renders your HTML on the server and delivers it for display to the client. And, typically, that HTML is designed to respond to users interaction with the page by posting back to the server. Your controller methods interpret these postbacks, perform the required logic, and render the correct razor page in response. But this isn't the only way to write a website.
More and more common, people are designing Single Page Applications. These use ajax callbacks to send the result of user actions back to the server, and then process the response. Server side, these requests are almost always handled through a WebApi controller method, not an ASP.NET MVC controller method. The request comes across the wire as ajax, and the result is usually returned as ajax. No HTML gets rendered. This is where MVVM comes into play.
Client side, these web pages typically use a javascript MVVM (ish) framework, like knockoutjs or angular. The response json is used to update view models that are bound to HTML elements in the web page. These frameworks handle synchronizing updates and user actions between the UI and these view models, just like Bindings synchronize updates between the UI and your view models in WPF.
Simply put, MVC is its own thing, and MVVM usually only exists within the client side of a website, and usually only when the website extensively uses ajax callbacks instead of postbacks.
And, to answer your direct question, if you're using MVVM on the client side, using ajax calls to perform your CRUD ops, you should design your WebApi controller methods to Post/Get/Put/Delete your data.
Personally, I always use the Repository Pattern for anything to do with CRUD operations, such as interacting with an entity in a database.
I would create a separate class called "ProductRepository" and put all the methods to Get, Create, Update, and Delete a Product in that class. This way, only your Respository cares about the details of interacting with the database and performing the CRUD operations on it. Your entire application should not care about how this gets done, only your Repository class. This is something known as the Single Reponsibility Principle. It is part of the "SOLID" principles of design and architecture.
Then, in either your Controller or ViewModel or where ever you need it to happen, you just have to instantiate the ProductRepository and use its methods throughout your application.
If you use a separate Web API for your service layer and data access layer, then you don't really need MVC. You just need a front-end framework to consume the Web API URLs, like AngularJS or any other JS framework of your choice.
If you want to use MVC, then you don't really need Web API. You can just build your service layer and data access layer into the MVC application, or build them as separate projects (class libraries) and include them in your overall project solution. It all just depends upon how you want the architecture to be and how complex you want to go with it.
But either way, a "ProductRepository" should be involved -- whether it is in your Web API (if you go that route), or in your MVC project (if you go that route). The ultimate goal is to have separation of concerns. You want to separate your business logic layer from your data access layer. You don't want to be making direct calls to the database throughout your entire application. That will result in code that is very tightly coupled and hard to test and maintain over time. If you ever change out databases in the future, you only want to update one place in the code, instead of many places.
Hope this helps you out some! Best regards and happy coding!!!
I trying to build an ASP.NET MVC application using Nhibernate and Structuremap along with the Repository pattern.
Through my initial approach to this project and the subsequent reading, I was wanting to keep the Nhibernate Session confined to the Repositories, and the Repositories to the Controller. But at the same time, in regards to transactions, I wanted to keep this separated from the repository methods (i.e. I just wanted to call session.Save()).
But It almost seems required that the Controller know about the session so that I can perform any transaction setup on the session before any Controller action, and any persistence to the database after the action using something like (i.e. the ActionFilterAttribute methods BeforeExecution or AfterExecuted, or BeginRequest/EndRequest events in the MvcApplication.
So in my mind I am having to give the current NHibernate Session to the Controller as well as the Repository, just so I can act on the Session when certain actions/results occur on the controller.
Is this the only way I can go about this?
I have read Ayende's blogs, and an assortment of different ways to go about this, but in the case of using the repository pattern, this almost seems like a must. I was hoping to be able to make the Nhibernate / StructureMap setup to the most pluggable way possible so with the exception of defining FluentNhibernate configuration for a specific project, there would be very minimal wiring for adding it to another MVC project.
That's ok. You'll need to open your session on your request begin and close it on your request end.
I've just started working on a WCF services project using web.api to expose data for a mobile version of our existing asp.net mvc web application.
So far I have used this WCF web.api getting started tutorial to get something running, with fake data created in the ServiceContract.
The service contract looks like this:
[WebGet(UriTemplate = "")]
public IQueryable<Workspace> Get()
{
//I want to use our existing service layer like this:
//WorkspaceService service = new WorkspaceService();
//service.ReturnAllWorkspacesByUsername("mary");
//this is fake data for testing
var workspaces = new List<Workspace>()
{
new Workspace() {Id = new Guid(), Title = "Implement WCF Web Services"},
new Workspace() {Id = new Guid(), Title = "Add APIs to WebService"},
new Workspace() {Id = new Guid(), Title = "Map Routes"},
new Workspace() {Id = new Guid(), Title = "Expose Resources"},
};
return workspaces.AsQueryable();
}
I would like to use the existing mvc application as much as possible, how can I use the existing service layer and domain model best, or is it best practice not to? Is it better to separate the services?
Can anybody point me towards some good beginner tutorials for this?
Thanks,
Kai
I prefer to have a common in-process business logic layer. DTO (data transfer objects) are used to communicate across layers. When data access layer is based on EF, I prefer to use POCO entities as by DTOs. Now, for external applications or different UI, I build different service layers - it will use same in process BL and DTOs to get the data. However, I prefer to have a separate Data Contract classes for services.
Logic behind separation is that the BL layer API can be more chatty (being in-process layer) while service API will be based on state-less chunky interactions. You may expose limited functionality and/or different API via services (because underlying impression is that services will be used by external applications). Its also advisable to have DTOs & DataContract separate because both can change in different way and at different times. Data Contract changes has to be controlled and versioned while same may not be applicable to DTOs (or domain objects).
As far as your mobile UI goes, it need not use services but rather directly depend on in-process BL layer. This is possible if your original MVC application is a layered one.
Another observation - it does not make sense to return IQueryable from the WCF service. You can return an array of objects and client app can cast to IQueryable if needed.
Currently I am working on small application in asp.net mvc. It is a some kind of localization tool. Our clients login on our application and they can translate terms that shows up in our applications that they use. It is happens like this:
login to localization site
find and translate certain terms for example title for button in "Catalog" application
start that application(for example, "Catalog" application from 2.) and trough web services they update local database of terms with these that are translated
It is our old solution and that works fine.
But now, I am doing refactoring of a translating tool application in asp.net mvc and I think, why we have separate logic(doubled) in mvc and in web services? Why we can't use only mvc as a web service...this way I have only one logic(fetching elements and updating) and we don't need to create wcf web service or something. And most important, I don't have mesh desktop applications with dependency on dll's in which I have this logic.
And now the question. What I can get from controller in mvc, except of views and JsonResults...can I get collections of my objects directly?
Or more plain question, how I can use asp.net mvc as a web services. What is your experience?
cheers
Marko
It really depends on your needs. You can most certainly use an ASP.NET MVC application as a data service, but it sounds like you should tease out your shared code into a common library and reference that library in both applications. There are some things that web service projects provide that would be more difficult purely as a controller action. (de/serialization, wsdl, etc...)
It really depends on what will consume your web service.
For example: jQuery consumes JsonResults well because i can return complex objects (with collections, arrays, nested objects etc) from an action and have jQuery deserialize it back to javascript object for use in the clients browser. Of course you loose type safety with the serialization process but that's pretty expected in most REST/SOAP based web services. If you really need the type safety for the consuming application, stick with WCF (or similar).
I'd just create a flag to return an action as Json. I've noticed a few sites do it this way. Say you have this action:
public ActionResult GetPeople()
{
IList<Person> result = svc.GetPeople();
return View(result);
}
..this action's result is normally rendered into some view. That's great, but if you want to use the action as a web service, you could simply change it to this:
public ActionResult GetPeople(string ajax)
{
IList<Person> result = svc.GetPeople();
if (Convert.ToBoolean(ajax))
return Json(result);
else
return View(result);
}
..so if your consuming app didnt mind the serialized Json then instead of invoking the GET request like this http://domain.com/controller/GetPeople (as a browser would to get the View), you'd just add the ajax flag like so http://domain.com/controller/GetPeople?ajax=true to return the Json. A more appropriate flag might be 'json' instead of 'ajax' - 'ajax' is common because this method is used to support downlevel browsers for actions that may optionally be invoked with ajax.
I've been thinking of adding this to my mvc app for a while but i don't like the idea of modding every action with this flag and add more if statements. My idea is to create a custom attribute to decorate actions that you want this functionality for and the attribute dynamically adds the extra flag and conditionally returns the model data as Json rather than what's originally specified. Give it a go.