MVC create a view model from multiple domain models distantly related - c#

I have been searching for a way to join 2 distantly related domain models into one view model with no luck.
I am working on an existing application and have been asked to add a field to a result of fax log search.
My controller is returning a viewModel, and I am just wanting to add an additional field to it. Which sounds like it should be an easy task.
Background Info:
This is the original viewModel:
public class VOEIFaxLogSearchListViewModel
{
public DateTime DateTimeAdded { get; set; }
public string Processor { get; set; }
public string FaxStatusCode { get; set; }
public string VendorOrderID { get; set; }
public string FromFaxNumber { get; set; }
}
I want to add an additional field to this viewmodel:
public string CustomerName { get; set; }
The way that the application is designed, a stored procedure is called to return a dataset of the search results. (I won't the search method (GetFaxLogSearchResult) or its SQL call as it isn't necessary)
var resultFaxDS = vOEIDAO.GetFaxLogSearchResult(startDate,endDate,userName,faxType);
The resulting DataSet is then converted to a DataTable.
DataTable faxTable = resultFaxDS.Tables[0];
A For loop interates through each of the result records and puts them into a Domain Model named FaxModel. Which is mapped with Automapper to the viewModel named FaxLogSearchListViewModel.
for (int i=0; i<faxTable.Rows.Count;i++)
{
var row = faxTable.Rows[i];
var faxLogModel = vOEIDAO.DRToFaxModel(row);
faxViewModel.Add(Mapper.Map<FaxModel,FaxLogSearchListViewModel>(faxLogModel));
}
}
return faxViewModel;
}
Here is what I have done so far to add this result field:
1) added the new property to the view model.
2) modified stored procedure that pulls back the search results so it returns CustomerName in the dataset
The dilemna:
The method adding each row of the dataset into the Domain model (DRToFaxModel) is doing just that... it is populating a domain model(FaxModel). The field that I want to add isn't in the Domain model.
As a result, I don't want to add a field to the domain model if it doesn't belong to the concrete class.
Here is the domain model and the method used to populate it with each row from the search results:
public class FaxModel
{
public int FaxID { get; set; }
public int FaxStatusID { get; set; }
public string ToFaxNumber { get; set; }
public string FromFaxNumber { get; set; }
public DateTime DateTimeAdded { get; set; }
public string FaxStatusCode { get; set; }
public string Processor { get; set; }
public string VendorOrderID { get; set; }
}
public FaxModel DRToFaxModel(DataRow dr)
{
FaxModel voObj = new FaxModel();
voObj.FaxID = GetVOInt(dr["FaxID"]);
voObj.FaxStatusID = GetVOSmallInt(dr["FaxStatusID"]);
voObj.ToFaxNumber = GetVOStr(dr["ToFaxNumber"]);
voObj.FromFaxNumber = GetVOStr(dr["FromFaxNumber"]);
voObj.DateTimeAdded = GetVODateTime(dr["DateTimeAdded"]);
voObj.FaxStatusCode = GetVOStr(dr["FaxStatusCode"]);
voObj.Processor = GetVOStr(dr["Processor"]);
voObj.VendorOrderID = GetVOStr(dr["VendorOrderID"]);
//Cant add CustomerName to the model without modifying the FaxModel domain model.
//Shouldn't do that because it is a domain model.
//CustomerName is in the CustomerModel domain Model
// voObj.CustomerName = GetVOStr(dr["CustomerName"]);
return voObj;
}
So currently, my ViewModel with the added CustomerName property is returned with a null for CustomerName.
My domain models are distantly related.
In the database the FAX table can be joined joined to the CUSTOMER table but only by joining through an ORDER table. (the FAX table has an orderID field and the ORDER table has a CustomerID field)
So my resulting question is:
how do you use autoMapper to map a Fax domain model to a Customer domain model since the 2 domains don't have any common fields to build the relationship without joining through another table?
Or can you map more than 2 tables into 1 viewModel using automapper? how is this done?

What a great question. First of all, it's so refreshing to see someone asking about the proper way to do something, rather that just seeking a quick fix. Second, the amount of documentation provided is exactly the way SO questions should be written. I wish I could give this more than +1.
That said, since you're essentially asking an architecture question, there aren't any concrete answers, just opinions.
Here's my opinion:
You state the result of the sproc is mapped to a domain model:
var resultFaxDS = vOEIDAO.GetFaxLogSearchResult(startDate,endDate,userName,faxType);
However, you've added a return field, CustomerName to your sproc which is not part of the domain model. I think that's the heart of your issue.
There's a choice to be made here: does this sproc return a domain model or doesn't it?
Right now, my opinion is that it does not represent a domain model anymore, due to the new field, so you should not be trying to map it to a domain model before mapping it to your view model. You need to create a new data type to map this result to, which represents what you are actually getting from the sproc, and map that to your view model.
The alternate option is that this sproc does in fact represent a domain model. If that is the case, you should not be adding a new field to it that is not part of the model. Rather, you'll need to get the FaxModel domain objects and CustomerModel domain objects separately, and assemble your view models from both objects.
This is an example of the Single Responsibility Principle, meaning that an object, function, assembly, heck, even a program, should have one purpose. By giving your sproc a return value that both is and isn't a domain model, you're giving it more than one purpose. It would be best to either decide that it represents a FaxModel, and accept that the customer name needs to come from another source, or decide that it returns something else, say CustomerFaxModel which contains both customer and fax information, and use it as such.
To answer your technical question, AutoMapper does allow you to pass an existing target object to the map function in addition to a source object. You can map the target from object A to get some fields, and then pass the already mapped target to Map() a second time with a source of object B to map other fields.
Always, always, keep asking questions like this and you'll do well.

Related

ASP.net working with entities

I have some kind of misunderstanding of working with entities in asp.net mvc concept.
I am pretty new to asp.net mvc and when I was studying I was told that whenever I work with databases I have to create a Model which will be a copy of generated by EF. And sending to views and all the calculations are done with that model..
For example if I have entity Person with something like:
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Nullable<System.DateTime> DateOfBirth { get; set; }
I have to generate class (EmployeeViewModel) in my Model folder:
public class EmployeeViewModel
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Nullable<System.DateTime> DateOfBirth { get; set; }
}
and in my controller I was usually doing something like this to get data about one Employee from database to my model (something similar if list of employees):
var Employee = db.Employees.Where(item => item.EmployeeId == someId).Select(item => new EmployeeViewModel
{
EmployeeId = item.EmployeeId ,
FirstName = item.FirstName ,
LastName = item.LastName ,
DateOfBirth = item.DateOfBirth
}).FirstOrDefault();
This code works, but the concept of working with this custom model, which is just a copy of an entity seems to be strange.. I understand that this concept of creating custom models is useful if our custom model differs from the entity.
So do I have to do it anyway, or I can work straight with entities in some cases. I would be glad if you could recommend some articles or something else to get the idea, how do I have to work with databases in my mvc projects, so as it would be correct in sense of its original concept.
You don't have to create copies of all of your models. In fact, if they are nothing more than carbon copies which don't add any value of any kind, then you really shouldn't be making them.
Just about any C# class can be the model that is bound to the view. If your Entity Framework model fits the business need of the view, then there's little-to-no value in adding a translation layer between the two.
There is often personal preference in which the developer wants to keep the database models and the application models separate. The objective need for this separation depends on the architecture of the system being built. (No details of which are described in this question.)
Conversely, there's equally an argument to be made of a single set of dependency-free business models which are used throughout every layer of the application. This side is often proposed by asking the question... If your use case (what the user does in the view) doesn't line up with your system architecture, shouldn't the latter be changed to better facilitate the former?
In short, you certainly can create a hard line of separation between different classifications of models for different layers of the application. But whether or not you should is a larger matter. If in your case doing so creates additional work and additional complexity without any additional value, then that seems to indicate that it's not necessary.

Use AutoMapper to map two VM to one Entity object

I'm using AutoMapper to map a lot of Entity models to View Model that I use in my controllers and views (.Net MVC)
There is a lot of relations in the DB and so our VM have a lot of childs (who have childs, and so and so)
public class InvoiceVMFull : VMBase
{
public int Id { get; set; }
public InvoiceType InvoiceType { get; set; }
public string Reference { get; set; }
//.... shortened code for readability
// list all entity fields
public List<string> InvoiceMainAddress { get; set; }
public List<string> InvoiceDlvAddress { get; set; }
}
It works just fine, but is very slow and always load from the DB all relations whereas I usually need only a few datas...
So I created some light VM that I want to use for the majority of our pages.
public class InvoiceVMLite : VMBase
{
public int Id { get; set; }
public string Reference { get; set; }
//.... shortened code for readability
// list only some of the entity fields (most used)
public StoredFileVM InvoiceFile { get; set; }
}
The problem is I can't find how :
to map one Entity object to the two VMs and how to choose the right one (to load from DB) using the context (the page or event called)
to map two VMs to one entity and save (on the DB) only the fields that are present in the VM used and don't erase the absent ones
I tried to create the mapping both VM :
Mapper.CreateMap<Invoice, InvoiceVMLite>();
Mapper.CreateMap<Invoice, InvoiceVMFull>();
But when I try to call the mapping for Lite, it doesn't exist (have been overridden by Full) :
Mapper.Map(invoice, InvoiceEntity, InvoiceVMLite)
Correct Use of Map function
It looks like you are calling map incorrectly. Try these instead
var vmLite = Mapper.Map<Invoice, InvoiceVMLite>(invoice);
var vmFull = Mapper.Map<Invoice, InvoiceVMFull>(invoice);
var vmLite = Mapper.Map(invoice); // would work if it were not ambiguous what the destination was based on the input.
Entity to two view models
You would usually create two mappings, one for each view model from the one entity. I'd suggest the cleanest is to have two separate views (separate Actions in a controller) for each view model. This may involve a quick redirect after you've decided on context which one to use.
View models to entity
Automapper is not meant for mapping from view models to Entities for many reasons, including the challenge you'd face. Instead you would pass specific parameters. The author of Automapper, Jimmy Bogard, wrote a good article on why this is the case.
I couldnt manage to do that with AutoMapper, and so I created my own convert methods (Entity <=> VM) with a lot of reflexivity, and with specific cases handled in each of the VM classes.
Now I can easily get a full or lite VM from an Entity, and also specify the depth in relation I want to go. So it's A LOT faster and more adaptable than AutoMapper
And I can save a VM to an entity (only saving modified fields if I want) that I create or that i got from base. So it's A LOT faster and adaptable than AutoMapper
In conclusion : Don't use autoMapper, it seem easy but create so many performance issues that it isn't worth it

Entity Framework Invalid column name when adding property that is not in db table

I had decided that there are just too many things that need to be different on the View Presentation Layer compared to what is actually in the database table.
I have a class of properties in C# that represents the model of my database
HOWEVER I was reading about ViewModels and I can see how they can do the nice things of not displaying containing an unnecessary amount of data that you do not wish to display on your view, and it can also be an important aggregrate of combining multiple models in which you have much more available to you for trickling down to the View.
I simply tried to add a class with a property
public class ExtendedFile
{
public string FileSize { get; set; }
}
Then I figured I could simple add this as another property to my other model class , so I added it
public ExtendedFile ExtendedFile { get; set; }
Then it seems that I can in my controller simply hydrate this
file.ExtendedFile.FileSize = ConvertFileSize(file.size);
So then my View now has
<td>#item.ExtendedFile.FileSize</td>
Well that did not work out .. A controller method had code in it in which a linq query that joins 2 tables freaked out. The error message is:
Invalid column name 'ExtendedFile_FileSize'.
The code that causes the error is:
var query = (
from qtips in dbProd.tblTips
where qtips.id == 30
join files in dbProd.tblFiles on qtips.id.ToString()
equals files.#group select new { qtips, files }).ToList();
Add the attribute as [NotMapped] on the property which is not column of database
Thanks to Stephen while I realize that I "can" do use this other model, I'm just going really against the proper patterns in which what a true ViewModel is for
Thus I already had this working 40 minutes ago by simply adding the [NotMapped]
[NotMapped]
public ExtendedFile ExtendedFile { get; set; }
It exposes a bigger issue of the fact that I was not understanding the ViewModel.
So while that "works" I am going to instead have a ViewModel with
The properties I want to display from the tblFiles class
The properties from this this ExtendedFile class such as
public class ExtendedFile
{
public string FileSize { get; set; }
//more properties
}
This means that it can not find a field of the database that defined in the model.
For example, my problem was that I had written the "Connection string" with the test database wrong.

ASP.Net - Create Entity Class From Query Fields - Visual Studio

I am very new to ASP.Net and MVC applications so pardon me if this question has been asked or is trivial.
I know how to create an entity model class from a database table, but I want to perform a series of Joins and create a Pivot table from an SQL query and then pass this to a view.
However, I do not know a quick way to create an entity class for this.
Currently, I am doing it the long way by manually defining a model class like so:
public class OAData
{
public int Zone { get; set; }
public string Device { get; set; }
public string Part { get; set; }
...
//CONSTRUCTOR
public OAData(int zone, string device, string part...){
Zone = zone;
Device = device;
Part = part;
...
}
}
and then create a database connection in the controller, loop through all the records, creating OAData objects for each record, add it to a list and then pass that list to the View.
Is there an easier way to do this (there are many fields returned by the query)? Can I create a model from a complex SQL query rather than just off a database table?

N-tier Repository POCOs - Aggregates?

Assume the following simple POCOs, Country and State:
public partial class Country
{
public Country()
{
States = new List<State>();
}
public virtual int CountryId { get; set; }
public virtual string Name { get; set; }
public virtual string CountryCode { get; set; }
public virtual ICollection<State> States { get; set; }
}
public partial class State
{
public virtual int StateId { get; set; }
public virtual int CountryId { get; set; }
public virtual Country Country { get; set; }
public virtual string Name { get; set; }
public virtual string Abbreviation { get; set; }
}
Now assume I have a simple respository that looks something like this:
public partial class CountryRepository : IDisposable
{
protected internal IDatabase _db;
public CountryRepository()
{
_db = new Database(System.Configuration.ConfigurationManager.AppSettings["DbConnName"]);
}
public IEnumerable<Country> GetAll()
{
return _db.Query<Country>("SELECT * FROM Countries ORDER BY Name", null);
}
public Country Get(object id)
{
return _db.SingleById(id);
}
public void Add(Country c)
{
_db.Insert(c);
}
/* ...And So On... */
}
Typically in my UI I do not display all of the children (states), but I do display an aggregate count. So my country list view model might look like this:
public partial class CountryListVM
{
[Key]
public int CountryId { get; set; }
public string Name { get; set; }
public string CountryCode { get; set; }
public int StateCount { get; set; }
}
When I'm using the underlying data provider (Entity Framework, NHibernate, PetaPoco, etc) directly in my UI layer, I can easily do something like this:
IList<CountryListVM> list = db.Countries
.OrderBy(c => c.Name)
.Select(c => new CountryListVM() {
CountryId = c.CountryId,
Name = c.Name,
CountryCode = c.CountryCode,
StateCount = c.States.Count
})
.ToList();
But when I'm using a repository or service pattern, I abstract away direct access to the data layer. It seems as though my options are to:
Return the Country with a populated States collection, then map over in the UI layer. The downside to this approach is that I'm returning a lot more data than is actually needed.
-or-
Put all my view models into my Common dll library (as opposed to having them in the Models directory in my MVC app) and expand my repository to return specific view models instead of just the domain pocos. The downside to this approach is that I'm leaking UI specific stuff (MVC data validation annotations) into my previously clean POCOs.
-or-
Are there other options?
How are you handling these types of things?
It really depends on the projects architecture for what we do. Usually though.. we have services above the repositories that handle this logic for you. The service decides what repositories to use to load what data. The flow is UI -> Controller -> Service -> Repositories -> DB. The UI and/or Controllers have no knowledge of the repositories or their implementation.
Also, StateCount = c.States.Count would no doubt populate the States list anyway.. wouldn't it? I'm pretty sure it will in NHibernate (with LazyLoading causing an extra select to be sent to the DB).
One option is to separate your queries from your existing infrastructure entirely. This would be an implementation of a CQRS design. In this case, you can issue a query directly to the database using a "Thin Read Layer", bypassing your domain objects. Your existing objects and ORM are actually getting in your way, and CQRS allows you to have a "command side" that is separate and possibly a totally different set of tech to your "query side", where each is designed to do it's own job without being compromised by the requirements of the other.
Yes, I'm quite literally suggesting leaving your existing architecture alone, and perhaps using something like Dapper to do this (beware of untested code sample) directly from your MVC controllers, for example:
int count =
connection.Query<int>(
"select count(*) from state where countryid = #countryid",
new { countryid = 123 } );
Honestly, your question has gave me a food for thought for a couple of days. More and more I tend to think that denormalization is the correct solution.
Look, the main point of domain driven design is to let the problem domain drive your modeling decisions. Consider the country entity in the real world. A country has a list of states. However, when you want to know how many states a certain country has, you are not going over the list of the states in the encyclopedia and count them. You are more likely to look at the country's statistics and check the number of states there.
IMHO, the same behavior should be reflected in your domain model. You can have this information in the country's property, or introduce a kind of CountryStatistics object. Whatever approach you choose, it must be a part of the country aggregate. Being in the consistency boundary of the aggregate will ensure that it holds a consistent data in case of adding or removing a state.
Some other approaches:
If the states collection is not expected to change a lot, you can
allow a bit of denormalization - add "NumberOfStates" property to the
Country object. It will optimise the query, but you'll have to make
sure the extra field holds the correct information.
If you are using NHibernate, you can use ExtraLazyLoading - it will
issue another select, but won't populate the whole collection when
Count is called. More info here:
nHibernate Collection Count

Categories