I have a requirement to encapsulate pieces of business logic within a transaction in an OData Web API service. Some of these pieces will need to accept one or more entities.
An example use case might be StockProduct and this might accept a Product entity and a Location entity. It would create the product and update stock records for the Location.
The approach I've taken is to create an unbound OData action that accepts these entities so that both of these can be operated on in a single transaction. Unfortunately neither can Entities be used as an ODataActionParameter nor can they be part of a class and used as a complex parameter.
I can think of a two ways around this:
Create a DTO class that is not an entity that is a mirror of each of my mirror classes and convert from DTO to Model within my action. The problem here is that I already have a DTO for each Model eg. Product.cs and ProductDTO.cs and don't really want to have to create a third class. (Currently, the ProductDTO.cs is used for Posts, Puts, Patches and Deletes and the Product.cs is used for Gets).
Abandon OData actions and create a simple end point that accepts whatever I like. I'm not keen on going down the second route as I'd like to use OData exclusively.
Any thoughts or suggestions?
You can use the ActionConfiguration.EntityParameter() method to bind an entity as a parameter to your OData action method.
Here is an example:
ActionConfiguration validate = ModelBuilder.EntityType<TEntity>()
.Collection.Action("Validate");
validate.Namespace = "Importation";
validate.EntityParameter<TEntity>(typeof(TEntity).Name);
validate.CollectionParameter<string>("UniqueFields");
validate.Returns<ValidationResult>();
However, note that the ModelState will not check against the content of the supplied Entity and will set any missing properties to null and properties exceeding the StringLength(x) annotation in your model will still pass. If you wish to validate the entity itself after, use this bit of code in your action method:
[HttpPost]
public virtual IHttpActionResult Validate(ODataActionParameters parameters)
{
//First we check if the parameters are correct for the entire action method
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
else
{
//Then we cast our entity parameter in our entity object and validate
//it through the controller's Validate<TEntity> method
TEntity Entity = (TEntity)parameters[typeof(TEntity).Name];
Validate(Entity, typeof(TEntity).Name);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IEnumerable<string> uniqueFields = parameters["UniqueFields"] as IEnumerable<string>;
bool result = Importer.Validate(Entity, uniqueFields);
return Ok(result);
}
}
As for your StockProductDTO, it seems to me that this is an new Business Entity by itself and should be treated as such.
You can use a batch request to perform multiple operations within a single request. This allows you to use your existing controllers for inserting your two objects.
https://aspnetwebstack.codeplex.com/wikipage?title=Web+API+Request+Batching
Related
I have an odata call that works properly the first time but fails during any successive call due to properties not matching. My controller has very little logic as it's just responsible for calling my domain service to query an Entity Framework database and returning the results as view models. However, when I try to sort I get an error because the hierarchy of my view model does not match my domain model.
Domain Model:
public class Parent
{
public object Child
{
public string Name
}
}
View Model:
public class Parent
{
public string ChildName
}
Using the above examples the EF query would return a list of Parents, which I would convert to view models to send off to the client. When a sort request is made on ChildName odata fails because Parent has no concept of ChildName. I need to map ChildName to Child.Name. I've seen examples of people using EntitySets to change the name but none that will map the model in my case.
I ended up using EF to convert my domain model to a view model using a LINQ expression during the query. Example but changed the view model to ParentView and added constructor:
var query = from p in context.Parent select new ParentView(p.Child.Name)
The positive of this is that it's all run on the database so I'm not transporting unnecessary data. Also, I am able to continue to use the odata options in the query since odata will add onto the query. However, I can't help but feel this is not the best way.
In an ASP.NET MVC project we are using AutoMapper to map from domain model to viewmodel - and sometimes also flattening a hierarchy while doing so. This works like a charm and makes the rendering logic of our views very lean and simple.
The confusion starts when we want to go the other way from viewmodel (or postmodel or editmodel) to domain model, especially when updating objects. We can't use automated/two-way mapping because:
we would have to unflat the flattened hierarchy
all properties on the domain model would have to be mutable/have public setters
the changes coming from the view isn't always just flat properties being mapped back to the domain, but sometimes need to call methods like "ChangeManagerForEmployee()" or similar.
This is also described in Jimmy Bogards article: The case for two-way
mapping in AutoMapper, but the solution to this isn't described in detail, only that they go:
From EditModel to CommandMessages – going from the loosely-typed
EditModel to strongly-typed, broken out messages. A single EditModel
might generate a half-dozen messages.
In a similar SO question there is an answer by Mark Seeman where he mentions that
We use abstract mappers and services to map a PostModel to a Domain Object
but the details - the conceptual and technical implementation - is left out.
Our idea right now is to:
Recieve a FormCollection in the controller's action method
Get the original domain model and flatten it to viewModelOriginal and viewModelUpdated
Merging the FormCollection into viewModelUpdated using UpdateModel()
Use some generic helper method to compare viewModelOriginal with viewModelUpdated
Either A) Generate CommandMessages a la Jimmy Bogard or B) Mutate the differences directly into the domain model through properties and methods (maybe mapping the 1-1 properties directly through AutoMapper)
Can someone provide some examples of how they come from FormCollection through editmodel/postmodel to domain model? "CommandMessages" or "abstract mappers and services"?
I use the following pattern:
[HttpPost]
public ActionResult Update(UpdateProductViewModel viewModel)
{
// fetch the domain model that we want to update
Product product = repository.Get(viewModel.Id);
// Use AutoMapper to update only the properties of this domain model
// that are also part of the view model and leave the other properties unchanged
AutoMapper.Map<UpdateProductViewModel, Product>(viewModel, product);
// Pass the domain model with updated properties to the DAL
repository.Update(product);
return RedirectToAction("Success");
}
You might want to consider CQRS(Command Query Responsibility Segregation - I think this might be the concept you were missing), possibly even with Event Sourcing.
It is basically a practice of separating the logic of reading from a data source and writing to a data source, might even mean having different data models for reading and writing.
This might be a good place to start: http://abdullin.com/cqrs/
Option C: Put it all in the controller action. Next, if that gets hairy, decompose into services (abstract mappers) or messages-as-methods (the command message way).
Command message way:
public ActionResult Save(FooSaveModel model) {
MessageBroker.Process(model);
return RedirectToAction("List");
}
And the processor:
public class FooSaveModelProcessor : IMessageHandler<FooSaveModel> {
public void Process(FooSaveModel message) {
// Message handling logic here
}
}
This is really just about moving the "processing" of the form out of the controller action and into individual, specialized handlers.
But, I'd only really go this route if controller actions get hairy. Otherwise, just take the form and do the appropriate updates against the domain models as necessary.
There are some similarities here with what I've been doing. My hierarchy of view models is only somewhat flattened from its domain object equivalents, but I do have to deal with calling explicit service methods on save to do things like adding to child collections, changing important values etc, rather than simply reverse mapping. I also have to compare before and after snapshots.
My save is Ajax posted as JSON to an MVC action and enters that action magically bound back to a view model structure by MVC. I then use AutoMapper to transform the top level view model and its descendants back into its equivalent domain structure. I have defined a number of custom AutoMapper ITypeConverters for those cases where a new child item has been added on the client (I'm using Knockout.js) and I need to call an explicit service method. Something like:
foreach (ChildViewModel childVM in viewModel.Children)
{
ChildDomainObject childDO = domainObject.Children.Where(cdo => cdo.ID.Equals(childVM.ID))).SingleOrDefault();
if (childDO != null)
{
Mapper.Map<ChildViewModel, ChildDomainObject>(childVM, childDO);
}
else
{
MyService.CreateChildDO(someData, domainObject); // Supplying parent
}
}
I do a similar thing for deletes and this process cascades quite nicely down through the whole structure. I guess a flattened structure could be either easier to work with or harder - I have an AbstractDomainViewModel with an ID with which I do the above matching, which helps.
I need to do comparisons before and after updating because my service layer calls trigger validation which can affect other parts of the object graph, and this dictates what JSON I need to return as the Ajax response. I only care about changes which are relevant to the UI, so I transform the saved domain object back to a new view model and then have a helper method to compare the 2 view models, using a combination of manual upfront checks and reflection.
I have An EntityModel that is named ECommerceEntities that contains several entities. If I want to use this model in a view in asp.net mvc, Can I pass ECommerceEntities instance to view or Sould I pass one entity in ECommerceEntities.
I mean :
//Can I use this?
public ActionResult Index()
{
ECommerceEntities entity = new ECommerceEntities();
return View(entity);
}
or
//Should I use this?
public ActionResult Index()
{
ECommerceEntities.OneEntity one_entity = new ECommerceEntities.OneEntity();
//filling one_entity here and then send to view
return View(one_entity );
}
Thanks.
If you are asking if it is possible, it is possible to do both. Yes, both options will work. However if you only need the sub entity in the view, I would just pass the sub entity into the view. No use in passing in more than needed right?
Do not forget that in MVC whatever object you pass in to your view,(EcommerceEntities for example) can have its properties set in the post by MVC's automatic model binding which maps data from the post into the object you pass into the view.
So, this means that someone can hijack the http post and can fill in EcommerceEntities and its sub entities with various bits of random data of their choosing if you are not careful and you may accidentally save this data to your db because you did not expect some of these properties to get set.
So, when working in MVC you have to protect properties that are not being used in your view but are passed into the view to ensure that nobody has injected them.
If you do decide to pass in EcommerceEntities, make sure that you use whitelisting or look at MVC's bind attribute to protect your data when your entity is posted back to your controller.
Because of the work involved in protecting that much extra data, I would say that the sub entity would be best if the screen will populate correctly just off of the sub entity object.
Hopefully this is helpful.
If you want to display a list of all entities (which the Index action is typically used for), you probably want to get all the entities from your database context:
public ActionResult Index()
{
// assumes dbContext is already initialized
ICollection<ECommerceEntities> entities = dbContext.ECommerceEntities
return View(entities);
}
I'm begginer in asp.net mvc and i have some doubts.
P.S: I'm using DDD to learn
I have an ACtion in a Controller and it'll save an entity (from my model) by a repository (for a database).
My doubts is, How can I get the informations from the View and save it by a repository in my Controller ?
Is it correct to get an entity of my Model in Save method of controller, like this:
public ActionResult Save(Product product)
{
// validate object
// save data in repository
return View("Success");
}
Or Need I get an DTO (with a structure similar to my entity) and create an object passing property by property to an entity ?
I didnt' like of FormCollection and I'd like to know, What is recommended architecturally ?
Thanks a lot guys
Cheers
I you want to follow DDD practices as described by the Blue Book you should bind your views to DTO's which can be forwarded to a thin 'Application' layer where Domain objects are created or retrieved from database. This application layer can be a simple facade with methods or can leverage command pattern.
For a live demo, you can see my project -- DDDSample.NET
This kind of problem can be fixed by adding so called view model.
Basically - a view model is DTO that provides data for particular view. In similar fashion - view models are used to get data back from view via model binding. Then - controller just forwards necessary data to domain model.
Typically, in ASP.NET MVC your controller actions will receive strongly typed objects returned by the DefaultModelBinder when editing entity types. Using this pattern you can pass a "Product" to your GET view either by itself or as part of a DTO and then your "Save" method would receive a "Product" object in its parameter list.
So long as you are using either editor templates or fields with matching names (i.e. Html.TextBox("Name") corresponds to Product.Name) then the DefaultModelBinder should be able to correctly fill the typed entity object passed to the action method. You shouldn't have to mess with the FormCollection except in certain edge cases.
[HttpGet]
public ActionResult Create() {
return View("Create", new Product());
}
[HttpPost]
public ActionResult Create(Product product) { //or Save(Product)
...
}
As long as your form has fields which match the fields in Product, they should automatically be populated for you based on the values. How you save the entity depends on the data model, whether you're creating a new record or editing an existing one, etc.
I have a simple form which inserts a new Category with the given parentID (ServiceID).
and my parent child relationship is this;
Service > Category
my url for creating a Category based on the ServiceId is this
/Admin/Categories/Create/3 => "3 is the serviceID"
and my Action method is this
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(int? id, Category category)
{
if (ModelState.IsValid)
{
try
{
category.Service = dbService.GetAll().WithServiceId(id.Value).SingleOrDefault();
dbCategory.Add(category);
dbCategory.Save();
return RedirectToRoute("List_Categories", new { ServiceId = id.Value });
}
catch
{
ModelState.AddRuleViolation(category.GetRuleViolations());
}
}
return
View ....
I am using LinqToSql for db actions. Anyway the strange part begins here.
When i save the data it inserts a data to Service table instead of insterting data just to Category Table and the data which is inserted to Category Table has the new inserted ServiceID.
Is it a problem with the ASP.NET MVC ModelBinder or am i doing a mistake that i dont see ?
I have used LinqToSql in several projects and have never had an issue like this
It could be an error in your LINQ To SQL set up. Is the service id an autogenerated field in the DB -- is it marked as such in the LINQ to SQL classes? Does your service disconnect it from the data context, then not reattach it before submitting? If so, have you tried adding the category to the service and then saving the updated service?
var service = ...
service.Categories.Add(category);
service.Save();
Where does your Category object come from? As I see you are relying on ASP.NET MVC Model binding for providing it but for that you need a form somewhere to make a POST. It would help to see the form too.
Also personally I rather use FormCollection (rather than business model classes) in my action signatures and then pull the posted data out from the FormCollection by myself. Coz sooner or later you end up having some complex objects with various one-to-many, many-to-many relationships that Model Binding just won't pick up and you have to construct it by yourself.