Domain Model with partially loaded objects - c#

Let's say I have an application which consists of both client and server. Client is using MVVM pattern (with WPF) and server is simply a WCF service which fetches some data from database and returns data as DTO-objects to client. In client, DataAccess layer converts these DTOs to domain objects and passes them to Model. ViewModel uses Model to fetch data (Domain Object) and populates itself with it.
To optimize database performance, each ViewModel is given only the data it really needs and nothing more (as recommended by many sources). For example, let's say there is an entity called DbCustomer which has 30 properties, and there are also 3 different Views related to customers: CustomerProfileView, CustomersListView and CustomerThirdView. Every view needs different portion of data: CustomerProfileView uses 20 properties, CustomersListViewuses 10 properties and CustomerThirdView uses only 4 properties. For each View, only required properties are fetched from database and delivered to ViewModel.
Now the problem arises: how should I design my Domain Objects to support this?
Solution 1, one partially loaded Domain Object (no-go)
If I have only one Customer Domain Object which is used by all ViewModels, it would have different data depending on the ViewModel that requested it. Obviously this is a no-go way because if I have to use this Customer object somewhere else I cannot be sure does it have enough properties loaded.
For example, I might have method GetDataStoragePath which is supposed to return string describing path to customer's private files. The method requires properties FirstName, LastName, SSN and IsExternalCustomer. Now, let's say CustomerThirdView doesn't need IsExternalCustomer, so it is not loaded when CustomerThirdViewModel requests Model to load Customer. Now if I use this Customer somewhere else (it is not a ViewModel specific object), the method GetDataStoragePath will fail.
Solution 2, three different Domain Objects
In another solution there would be 3 different Domain Objects (used as data containers) with suitable interfaces, and thenGetDataStoragePath would depend only from this interface. Example:
public interface ICanGetDataStoragePath {
string FirstName { get; }
string LastName { get; }
string SSN { get; }
bool IsExternalCustomer { get; }
}
public CustomerProfileData : ICanGetDataStoragePath { ... } // Implements interface
public CustomerListViewData : ICanGetDataStoragPath { ... } // Implements interface
public CustomerThirdViewData { ... } // Does NOT implement interface
public class CustomerLogic : ICustomerLogic {
public string GetDataStoragePath(ICanGetDataStoragePath customer) {...}
}
This would lead to Anemic Domain Model but it is not a problem in my opinion. However, it seems messy since I can easily imagine that there would be 20 different methods with different needs which would result in 20 interfaces (and only for Customer, there are LOTS of other domain objects also). Of course in this simple case I could pass all four parameters separately to GetDataStoragePath but in real life there are many more required properties.
Are there any other options? What would be the best way to solve the problem?

Your model obviously has to much Data. Why not make 3 models and one composite model?
i.e.
public class CustomerProfile
{
public string Phone { get; set; }
// other profile fields
}
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string SSN { get; set; }
public bool IsExternalCustomer { get; set; }
public CustomerProfile Profile { get; set; }
}
Then you'd put all of your always required fields into the Customer class and group the rest together, i.e. in a CustomerProfile class. If it's null, then that data wasn't fetched and isn't available

Related

Controller accepting different models

I want to accept different model type from body based on query param value.
Example:
[HttpGet]
[Route("GetSystemdetails")]
public string Getdeatils([FromBody] SystemDetail sysdetails, string type)
{
//some code here
string details = getdetails(sysdetails);
}
// abc model
public class abc
{
public int UserID { get; set; }
public string Email { get; set; }
}
//xyz model
public class xyz
{
public int xyzid { get; set; }
public string systemval { get; set; }
public string snum { get; set; }
}
type abc and xyz will have it's own model. So based on type I receive in query param I wanted to pick the model and proceed.
Sample url:
localhost/GetSystemdetails/type=abc
localhost/GetSystemdetails/type=xyz
I thought of creating a new model SystemDetail which holds these two models(xyz and abc) and based on system pick them.
I wanted to know what are possible ways to achieve this kind of requirements without creating multiple methods in controller(I don't want to change the format of the URL).
That's not something that's supported out of the box. Your linked solution is probably the closest you'll get to that.
ASP.NET Core is not supposed to take values of the parameters into account when routing, except for validation.
There are several possible ways to do so
Having multiple model objects
As in the link you provided, you can declare multiple model objects. The site has given the example of
public class PostUserGCM
{
public User User { get; set; }
public GCM GCM { get; set; }
}
but you can use your own examples.
Base model
Your models can inherit from some base model. If you only need a single model at a time and they share some similarities, then you could just create a base model which the other two are inheriting from, be agnostic at implementation time and your use cases will mainly differ on instantiation inside the controller, while some service methods could handle other differences.

Most efficient way to convert a object to another (Model to ViewModel)

Suppose I have a model with 20 fields, and in my index page, I want to list all models that are stored in my database.
In index page, instead of listing all fields of the model, I only to list 3 fields.
So, I make two class:
class CompleteModel {
public int Id { get; set; }
public string Field01 { get; set; }
public string Field02 { get; set; }
public string Field03 { get; set; }
public string Field04 { get; set; }
public string Field05 { get; set; }
...
public string Field20 { get; set; }
}
now, in my Controller, I can use:
await _context.CompleteModel.ToListAsync();
but I feel that it does not seem to be the right way to do it, because I'm getting all fields and using only 3 fields.
So, I made this code:
class ViewModel {
public string Field02 { get; set; }
public string Field04 { get; set; }
public string Field08 { get; set; }
}
var result = _context.CompleteModel.Select(
x => new {
x.Field02,
x.Field04,
x.Field08
}).ToListAsync();
var listResults = new List<IndexViewModel>();
if (result != null)
{
listResults.AddRange(results.Select(x => new IndexViewModel
{
Field02 = x.Field02,
Field04 = x.Field04,
Field08 = x.Field08
}));
}
I think this is a lot of code to do this.
First, I selected all the fields that I want, then, copied everything to another object.
There's a "more directly" way to do the same thing?
Like:
_context.CompleteModel.Select(x => new IndexViewModel { Field02, Field04, Field08 });
You could use AutoMapper to reduce the boiler plate so you're not manually copying field values over.
If you include the AutoMapper NuGet package then you'd need to have the following in your startup somewhere to configure it for your classes:
Mapper.Initialize(cfg => cfg.CreateMap<CompleteModel, ViewModel>());
You could then do something like the following:
var results = await _context.CompleteModel.ToListAsync();
var viewModelResults = results.Select(Mapper.Map<ViewModel>).ToList();
There are a lot of configuration options for the package so do take a look at the documentation to see if it suits your needs and determine the best way to use it if it does.
In my view this is one of the weaknesses of over abstraction and layering. The VM contains the data that is valuable to your application within the context of use (screen, process etc). The data model contains all the data that could be stored that might be relevant. At some point you need to match the two.
Use EF Projection to fetch only the data you need from the database into projected data model classes (using the EF POCO layer to define the query, but not to store the resultant data).
Map the projected classes onto your VM, if there is a naieve mapping, using Automapper or similar. However unless you are just writing CRUD screens a simple field by field mapping is of little value; the data you fetch from your data store via EF is in its raw, probably relational form. The data required by your VM is probably not going to fit that form very neatly (again, unless you are doing a simple CRUD form), so you are going to need to add some value by coding the relationship between the data store and the View Model.
I think concentrating on the count of lines of code would lead to the wrong approach. I think you can look at that code and ask "is it adding any value". If you can delegate the task to Automapper, then great; but your VM isn't really pulling its weight other than adding some validation annotation if you can consistently delegate the task of data model to VM data copying.

Smaller version of domain objects to send to a (low memory) client

I have domain objects with lots of properties (members) that I am using in my API. In some of the transactions, it makes more sense to send the domain objects to the client rather than a whole new response class with the same members
Now my question is, is there a way that I hide some properties of the class and only send some properties (members) to the client (and in a different call send a different set of properties and hide rest)?
You can create new response DTO(Data Transfer objects) classes containing the only properties you want to send back. Then create factory methods for converting your objects of Domain Classes to response DTO.
This will serve your purpose. Later if you want to add new properties in your DTO that actually exist in other domain classes you can add those easily.
Just to add in case you intend to use it. You can have Request DTO's as well, The client's data may not necessarily map to your domain classes. Again you can create a factory method that will convert your request DTO into domain class/classes object(s).
As already has been answered, DTO is more suited for this. As an alternative, you can "hide" unwanted properties from the client behind a more specific public interface. Your domain objects can simply implement them.
Example:
class Document : IEntity, IVersionable, IDocumentContentDescription
{
public string Name { get; set; }
public string Description { get; set; }
public string MimeType { get; set; }
public long Length { get; set; }
public int Version { get; set; }
}
public interface IDocumentContentDescription
{
string MimeType { get; }
long Length { get; }
}

Model inheritance - Repository Pattern with IoC

I am new to IoC and Repository Pattern. I was able to do some test project and it works. But, I am not so sure if what I implemented is a good practice. The test project I have created have all the repositories in place as well as a working interface with a dummy data. But what I want is that my project should not be able to know the concrete types of my models because the initial version should be implemented using MSSQL, and the second version would be a mix of MSSQL and NoSQL(for reads and logging). The models might have different properties or structures from MSSQL to NoSQL (or whatever i might use in the future)
So I tried to create an interface for each model:
public interface ISearchResult
{
string Id { get; set; }
string Name { get; set; }
string Description { get; set; }
string Url { get; set; }
}
And here's the repository:
public interface ISearchRepository<T> where T: class, ISearchResult
{
IEnumerable<T> Search<T>(string keyword, IEnumerable<string> regions, IEnumerable<string> industries,IEnumerable<string> countries, IEnumerable<string> cities, int offset);
}
And here's the service:
public interface ISearchService
{
IEnumerable<T> Search<T>(string keyword, IEnumerable<string> regions, IEnumerable<string> industries,IEnumerable<string> countries, IEnumerable<string> cities, int offset);
}
Because I want to have a working GUI even without MSSQL or NoSQL entities, I have created a View Model that inherited the ISearchResult:
public class SearchResultViewModel : ISearchResult
{
[Display(Name="Reference Id")]
public string Id { get; set; }
[Display(Name = "Company")]
public string Name { get; set; }
[Display(Name = "Description")]
public string Description { get; set; }
[Display(Name = "Website")]
public string Url { get; set; }
}
And here's how it looks on my controller:
[SearchQueryFilter]
[GeoTargetFilter]
public ActionResult Query(SearchQueryModel searchQuery)
{
searchQuery.Results = this._searchService.Search<SearchResultViewModel>(searchQuery.Keyword,searchQuery.Region, new List<string>() { searchQuery.Industries }, new List<string>() { searchQuery.Countries}, new List<string>() {searchQuery.City}, searchQuery.Offset)
.ToList<ISearchResult>();
return View(searchQuery);
}
And my view would look like this:
#foreach (SearchResultViewModel result in Model.Results)
{
//code to display
}
My question is: Is it fine to use this approach? I don't want my web application to be dependent on my data entities so that's why I came up of making my view models inherit an interface. And because I was new to IoC and Repository Pattern and only have a test project, I don't know if my solution would be more of a problem in the long run.
Any advise is highly appreciated.
You shouldn't need to implement an interface in your view model in order to create a separation between your web application and your data entities. Your view model should belong to your web application and should itself be independent of your data entity.
So, instead of:
_searchService.Search<SearchResultViewModel>(x);
You should have, in your controller:
var result = _searchService.Search<SomeEntity>(x);
var model = new SearchResultsViewModel
{
Name = result.Name,
Desc = result.Desc,
Url = result.Url
};
return View(model);
The view model belongs to the web application and is responsible for containing the data passed from controller to view (and back) - it should have nothing to do with your service layer (or any other layer of your application).
SomeEntity is a concrete class, in the form of whatever your search service exposes. Your controller will consume this in the same way as any other application would and then compile a view model for passing to and from views. You might even find that SomeEntity is more or less identical to SearchResultsViewModel initially; however, they are still distinct entities as the requirements of the view might change independently of the search service.

A viewmodel has a behavior/methods compared to a DTO but

People on SO often say:"A ViewModel holds methods that can be executed by the view, properties to indicate how toggle view elements, etc. ..."
When my ViewModel is sent as a WebApi response to the client serialized to JSON, how can this ViewModel execute a method on the client?
This is not clear at all to me.
You can understand viewmodel in at least two ways
instead of passing your business objects to the view (for example MVC Razor view) you pass stripped down objects that contain properties that are needed for this view and nothing else. View creation is easier and you avoid problems when view designer uses fields that are lazy loaded from database (avoid Select N+1 problem and others)
you can create viewmodel that will be used client side (in Javascript). You create it in Javascript as object and thus it can contain methods that view can call. What you are describing (sending JSON objects using WebAPI) is just data that will feed that viewmodel.
For example of this you can look on main page here knockoutjs. You can see TicketsViewModel that contains tickets array. In this example you can see three kinds of tickets hardcoded in viewmodel. But you could get them as JSON from WebAPI like you described. After downloading them just put them in this array.
A DTO (data transfer object) contains data in a consumable format. A ViewModel/ActionModel contains data formatted for the View to consume.
A DTO might look like:
public class OrderDTO
{
public decimal Price { get; set; }
public int Amount { get; set; }
}
While a ViewModel might look like:
public class OrderViewModel
{
public decimal Price { get; set; }
public int Amount { get; set; }
public string PriceBackgroundColor { get; set;}
public Uri ImageUri { get; set; }
}

Categories