I am new with ASP.NET Web API and have been researching this for some time now. Admittedly, I have decision paralysis. I want to make a REST-like API for a system with about 250 tables in the database. It's basically a 2 tier system with a UI and a data access layer, not using business objects or ORM.
I cannot decide if my Web API Controllers should accept/return:
a) IDictionary of name/value pairs, which I would package into sql parameters and pass to the data access layer and return a serialized ado.net data table
b) strongly typed complex object (POCO objects). For example: Account class with all properties matching up with fields in the database.
If I have to create POCO classes for every table in the system, there would be 250+ classes that essentially do nothing except package the data and pass it to our data access layer.
Further, it seems as if I need to create an ApiController for basically every table in the database that I want to expose via the Web Api because you only have GET, POST, PUT, DELETE per route? Please help, banging head on desk.
Please see answers below:
1.**Using **"IDictionary of name/value pairs" is fine if your resource supports GET methods only. If you want users to post or update data, how will you validate the data? In addition, if you want to add HATEOAS, how would you do that? In terms of extension, how would you support nested object hierarchy like the one below:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
public IList<PurchaseDetail> PurchaseHistory { get; set; }
}
public class PurchaseDetail
{
public int Id { get; set; }
public DateTime PurchaseDate { get; set; }
public decimal Cost { get; set; }
}
2. You can have more than one GET, POST,etc per resources by defining different routes. More from this link http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
Related
I am trying to develop an enterprise-level application. I have domain and application services. I have created my DTOs for multiple purposes separately. But confused about which way I should use them from the API viewpoint.
I have complex objects lets say,
public class Entity{
public int Id { get; set; }
public string Name { get; set; }
public int? ManufacturerId { get; set; }
public virtual Manufacturer Manufacturer { get; set; }
}
public class Manufacturer{
public int Id { get; set; }
public string Text { get; set; }
}
And I have corresponding DTOs designed with composition now. It was separated before.
public class EntityBaseDto{
public string Name { get; set; }
}
public class EntityReadDto : EntityBaseDto{
public string Manufacturer { get; set; }
}
public class EntityWriteDto : EntityBaseDto{
public int? ManufacturerId { get; set; }
}
Now the question is,
I have a table which is filled with List<EntityReadDto> which is clear. Before, EntityReadDto also had the ManufacturerDto as fully included with id and text. Whenever I require to edit one of the entries from the table I was able to load the dropdown selected items or list of tags etc with the ids attached to the Manufacturer objects within ReadDtos. Now it is not possible. Since I wanted to simplify the codes I just converted them to strings that are read-only. Now I have created another endpoint to get an editable version of the record when needed. Ex: EntityWriteDto will be used to fill the form when the edit is clicked on a specific item. The manipulation will be carried on that DTO and sent with the PUT type request to edit the record.
I am not sure if this approach is ok for these cases. What is the best practice for this? I have many objects related to the entities from other tables. Is it ok to make a call to get an editable version from the backend or need to have it right away in a VUEjs app?
I feel like this should be really simple but I am having an issue figuring out what is going on. I am working with a WCF service and have "Reuse types in all referenced assemblies" on. I have some simple classes to transfer some data. The classes show up fine and all the basic members show up, but no methods do. Are methods not included in this? Do I have to specify this is what I want somehow? Here is some example code. I just switched out my names to make it a little more generic.
public class Car
{
public string CarColor { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public string GenerateId()
{
return CarColor + Model + Year;
}
}
In this example I get CarColor, Model, and Year on the client side but not GenerateId.
So I ended up doing this a little different. It totally makes sense that only the data comes over. The problem is that I didn't want to have to have a new project to hold the data types. Its just a pain to have a new repository and a completely separate project for a handful of classes. Since I really only need the methods on the client side, I am just creating partial classes with them in it on the client side. That way I can pull the data structure from the service but still extend it to have the methods I need.
Service definition
public class Car
{
public string CarColor { get; set; }
public string Model { get; set; }
public int Year { get; set; }
}
Client partial class
public partial class Car
{
public string GenerateId()
{
return CarColor + Model + Year;
}
}
I've seen this (unanswered) question asked once before, but in a different context. I'm looking to have two domain objects map to the same table, WITHOUT a discriminator. The two classes are:
public class Category
{
public virtual int Id { get; private set; }
public virtual string Name { get; set; }
public virtual ReadOnlyCategory ParentCategory { get; private set; }
}
and
public class ReadOnlyCategory
{
public virtual int Id { get; private set; }
public virtual string Name { get; private set; }
public virtual ReadOnlyCategory ParentCategory { get; private set; }
}
The main difference is that all public properties of ReadOnlyCategory are read-only. My idea here is that I want all users of this class to know that they should only mess with the category they are currently 'looking' at, and not any other categories in the hierarchy. (I've left off other properties regarding the subcategories.)
Clearly, in the database, Category and ReadOnlyCategory are the same thing, and NHibernate should treat them very similarly when persisting them. There are three problems wrapped into one here:
1) How do I do the mapping?
2) When instantiating the objects, how do I control whether I instantiate Category or ReadOnlyCategory?
3) When persisting the objects, will the mapping be smart enough, or do I need to use an extensibility point here?
Any pointers on how I can get this to happen?
(Or am I crazy?)
This looks like wrong object model design to me. I don't see a good reason to introduce a new class just for authorisation reasons (whether user allowed to modify a given category object?). You may as well use one class and throw for example InvalidOperationException if an end user is not supposed to modify a category.
In employing Domain Driven design I often encounter an issue regarding the various perspective on a domain object, especially when using NHibernate. Perspectives are essentially ways to view an domain object. For example, a simplified model:
class Transaction
{
string Id { get; set; }
string CustomerName { get; set; }
DateTime Date { get; set; }
decimal Amount { get; set; }
decimal Tax { get; set; }
}
class Batch
{
string Account { get; set; }
string Number { get; set; }
DateTime? ClearDate { get; set; }
IList<Transaction> Transactions { get; }
decimal Total { get; }
}
The total property on the batch is the sum of the amounts on each transaction. When considering a single batch this model works well and is a proper representation of the domain. The client application however has a screen which displays collections of batches. That screen does not require any details about the transactions within a batch, only the total amount. Utilizing the same object on the listing screen is slow. One option is to make the Total property be settable, another option is to create a new class, such as:
class BatchOverview
{
string Number { get; set; }
decimal Total { get; set; }
}
This would have its own repository and its own NHibernate mapping to a database view.
Does this object belong to the domain model, or is it more application/GUI specific?
Should the batch overview object reference the batch object?
Is this a common pattern?
Is there any guidance in relation to this issue?
DDD has the concept of bounded contexts, however in this case the context is the same. Both the Batch class and the BatchOverview class refer to the same 'actual' batch - they are different views, or perspectives on it.
I would keep the new class out of the domain - it is a presentation concern in my book, and i would treat it as such. Normally this new object would be read-only so as not to having two ways of altering data (and one of them not having the full set of business logic contained).
However, you don't have to make a setter for the value just because you use nHibernate. Just make it use a backing field and let nHibernate write to that. (use access="field" in your mapping).
EDIT:
I call it a PresentationModel or ViewModel depending on the amount of logic inside.
I would probably keep a reference to the original object - but might only be an Id.
I'm creating a WCF service that transfers entity objects created via entity framework. I have a User entity that maps to a User db table. There are certain User fields (Password, DateCreated, etc) that I don't want to expose to the client but, because they are non-nullable in the db, Visual Studio requires mappings. Setting these properties as private seems like a good workaround but these properties are converted to public when consumed by a client.
Is there a way around this, or a better approach to take? I'd rather avoid changing these fields at the db level just to make EF happy.
This sounds like to perfect opportunity to segregate the layers of the application. What you should do is create objects that are specific to the WCF layer that act only as Data Transfer Objects (DTO) to the outside consumers.
So, in your WCF service layer you make will your calls to your data access layer (Entity Framework) which retrieves User objects and you should return to your consumer objects constructed with only what you want to expose.
If you do this, you can explicitly control what you make visible to the outside world and also hide any implementation details about what you are doing from a data storage perspective.
As an extremely crude example, in your Entity Framework layer you might have this object:
namespace ACME.DataAccessLayer.Entities
{
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Hash { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
namespace ACME.DataAccessLayer.Services
{
using ACME.DataAccessLayer.Entities;
public class UserService
{
public User GetUser(int id)
{
using (ACMEDataContext dc = new ACMEDataContext())
{
// psuedo code to return your user with Entity Framework
return dc.Users.FirstOrDefault(user => user.Id == id);
}
}
}
}
Then in your WCF later you might have an entity like:
namespace ACME.Services.DataTransferObjects
{
[DataContract]
public class User
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
}
}
Then you would expose a service endpoint that would return back the DTO as such:
namespace ACME.Services
{
using ACME.DataAccessLayer.Services;
public class PublicWCFService : IUserService
{
public ACME.Services.DataTransferObjects.User GetUser(int userId)
{
ACME.DataAccessLayer.Entities.User entityFrameowrkUser = new UserService().GetUser(userId);
return new ACME.Services.DataTransferObjects.User
{
Id = entityFrameowrkUser.Id,
FirstName = entityFrameowrkUser.FirstName,
LastName = entityFrameowrkUser.LastName
};
}
}
}
Now what you would do is just return the DTO object which will not have any of the attributes, or methods that you may have in the real entities you use in your system.
With this approach, you can safely break the layers of the application into different layers (DLLs) that can easily be shared and extended.
This is a quick example, so let me know if there's anything further that would make this example more clear.
You could always implement IXmlSerializable on the entity object. Then, you would be able to dictate the structure of what is sent to the client (the client would get a different representation, obviously).
Either that, or if you can, add the DataContract attribute to the type, and the DataMember attribute to only the properties you wish to send over the wire.