I have the below view models, which are used to represent a survey of questions, but they are structured into a more flattened grid to accommodate the default model binder.
// Main ViewModel for the Question View
public class SurveyRowList
{
...
public IList<SurveyRow> SurveyRowList { get; set; }
}
public class SurveyRow
{
public int QuestionId { get; set; }
public int? ParentQuestionId { get; set; }
public int SurveyId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string HelpInformation { get; set; }
public int RenderOrder { get; set; }
public SurveyRowType RowType { get; set; }
// Collection of the same answer control, 1 or more times
// for each line number
public IList<AnswerControl> AnswerControls { get; set; }
}
public enum SurveyRowType
{
QuestionGroup = 1,
Question = 2,
AnswerRow = 3
}
public class AnswerControl
{
public int Id { get; set; }
public int QuestionId { get; set; }
// a reference to the database record answer id
public int SurveyAnswerId { get; set; }
// control type of checkbox, dropdown, input, dropdown-additional-textbox, checkbox-group
public ControlType ControlType { get; set; }
// used to specify getting particular backing data for dropdown and checkbox-group
public ControlSpecificType ControlSpecificType { get; set; }
public string Description { get; set; }
public string HelpInformation { get; set; }
public int RenderOrder { get; set; }
public bool InLine { get; set; }
public int LineNumber { get; set; }
public AnswerControlValueType Value { get; set; }
}
public class AnswerControlValueType
{
// Default string backing value when possible
public string Value { get; set; }
// AnswerCheckBox
public bool CheckValue { get; set; }
// AnswerCheckBoxListModal
public string ModalName { get; set; }
// AnswerMultiSelectListValue
public int[] ListValues { get; set; }
// making the options list setter public so that this data can be re-attached after model binding
public IEnumerable<SelectListItem> ListOptions { get; set; }
// AnswerImageValue
public HttpPostedFileBase Image { get; set; }
// AnswerSelectListAdditionalValue
public string AdditionalInformation { get; set; }
}
Each SurveyRow is like a row of a table. Only the SurveyRowType.AnswerRow actually makes use of the AnswerControls list.
Example of their ordering when rendered by their type and order number can be seen in this image:
The image only shows a few simple examples, and there can be 1-10 lines per page to a max of 100, but I have also added a bit of explanation of some of the validation rules I would want to apply. There are more but these are just a few examples.
My problem is that I want to support this more complex validation but all the rules and error text are stored in a database, 1. because of user configuration, 2. because of existing localisation of the error text to support several languages.
I am looking for any suggestions that people might have to be able to support this.
I have seen things like Fluent Validation and I haven't delved too deep yet but so far I can't see any examples that would specifically not use Data Annotations on a model.. and also RequiredIf or DisabledIf or EnabledIf style validation rules that apply across a slightly more complex collection of objects.
I worked with MVC patterns in 2001 with servlets, and again in 2006, with a custom MVC framework implemented on top of ASP.NET, and looking at what people are doing nowadays makes me believe that most did not even care about looking at what MVC stands for, only that explain the models nonsense. A lot of developers working with ASP.net MVC, tend to bind the data that is coming from the client to models, but that is such a poor design. Models contain the data that should be forwarded to the template manager which is in most cases the Razor engine.
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
So my advice is: don't link the data that you get from the client into the models.
Get the data from the client, do a search on the Request object if it needs to
Validate the data (fluentvalidation)
apply the business rules
create the models
forward the models to the template engine
Also stopping using those crazy useless annotations.
My question was related to how I can support validating this complex model. I have since looked more at Fluent Validation and that has everything I need to do custom rules for a complex model, i.e. checking values across collections of objects within my model.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have an Article entity in my database:
public class Article
{
public Guid Id { get; set; }
public string Heading { get; set; }
public string Author { get; set; }
public string Content { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime UpdatedOn { get; set; }
public int ViewsCount { get; set; }
public ImageData Image { get; set; }
public IEnumerable<Comment> Comments { get; set; }
}
For the creation I have ArticleInputModel, and for displaying the details view, I have ArticleDetailsModel, and for update I have ArticleUpdateModel (etc....)
However those models have the same properties.
Should I separate this much if it means repetitions of code?
I try to follow SRP but this seems like is breaking DRY principle?
Am I overlooking something and what?
Should I separate this much if it means repetitions of code?
Usually, you can identify three situations with potentially different sets of properties when working with model classes (Data Transfer Objects; DTOs) for a single entity:
entity creation
entity reading (displaying, viewing)
entity updating
However, there may be many more subtypes — e.g. different ways to create or update an entity, partial vs. full update, various kinds of displays, e.g. full view, some kind of partial views, view of an entity in a list etc.
It does make sense to have a system in constructing DTOs, such that you differentiate between the create, read (view), update DTOs in respect to your Create, Read, Update operations. You can see a clear parallel between such DTOs and CRU(D) operations (there's typically no DTO for the Delete operation).
Regardless of the particular naming you use, such categorizations help future maintainability of your code: if, in the future, you need to introduce a property that may not be set during entity creation, but can be altered during an update, or vice versa, it is easy to do without extensive changes to unrelated parts of code, e.g. you change the updating path only, but avoid changing the creating path.
I try to follow SRP but this seems like is breaking DRY principle?
Providing the model (DTOs) classes are semantically different, then I don't see this as a violation of DRY. However, this may be subjective.
Think of DTOs as secondary objects. The primary declaration is the database entity, which is part of your data model. The various views of such an entity in the form of DTOs are dependent on this entity declaration. As long as you keep it to a simple public SomeType PropName { get; set; } in the DTOs, it is not a violation of DRY you couldn't live with. In addition, it makes sense to e.g. keep comments explaining various properties in entity declarations only, and not duplicate them into DTOs (unless you have to generate some API docs, but that's solvable with <inheritdoc/> as well). What's important, is the clear distinction between entities and DTOs and their roles.
If you're creating a new instance of an Article, what is it's Id?
Or as a more clear example, what will it's UpdatedOn date be?
How do you update something that doesn't exist yet?
One other issue you might come across very quickly is how are you going to return a list of all the articles by a particular Author?
In the Article table you should be storing Author as an Id linking as a foreign key to the Author table (assuming there can only be a single Author).
If your article table now looks like this...
public class Article
{
public Guid Id { get; set; }
public string Heading { get; set; }
public Id Author { get; set; }
public string Content { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime UpdatedOn { get; set; }
public int ViewsCount { get; set; }
public ImageData Image { get; set; }
public IEnumerable<Comment> Comments { get; set; }
}
...you might begin to see where separate ViewModels/DTOs come into play.
Create
public class CreateArticle
{
public string Heading { get; set; }
public IEnumerable { get; set; }
public string Content { get; set; }
public string Image { get; set; }
}
You're creating a new Article so will probably be inserting an auto generated Guid as the key. You'll also be fairly likely to be taking the current date/time as the CreatedOn date. Author would come from a lookup list of some description so you'd need to pass some sort of list into the View (simplified as IEnumerable above). The image is most likely going to be supplied from a path to the image location so you'd maybe want to display as a text box.
Add
public class AddArticle
{
public string Heading { get; set; }
public Id Author { get; set; }
public string Content { get; set; }
public ImageData Image { get; set; }
}
When you've filled in your Create form, you now want to add it to the db. In this case your DTO needs to add data in the format the db expects. So you'd now be passing the selected Author Id and maybe the ImageData after some processing magic elsewhere.
You still don't need an Article Id or CreatedOn as these will be added once this DTO has validated.
Details and View
Hopefully you're now seeing the slight differences that make the ViewModel a valuable asset. You might also require something like the following to show the details of an Article as opposed to viewing the Article itself:
public class DetailOfArticle
{
public Guid Id { get; set; }
public string Heading { get; set; }
public Author Author { get; set; }
public string Content { get; set; }
public string CreatedOn { get; set; }
public string UpdatedOn { get; set; }
public int ViewsCount { get; set; }
}
public class ViewArticle
{
public Guid Id { get; set; }
public string Heading { get; set; }
public string Author { get; set; }
public string Content { get; set; }
public string CreatedOn { get; set; }
public string UpdatedOn { get; set; }
public int ViewsCount { get; set; }
public ImageData Image { get; set; }
public IEnumerable<Comment> Comments { get; set; }
}
Notice that the details might pass in an Author entity so that you can supply more information (this could also be exploded out into separate properties). You might also want to pass the date (and/or time) as a string after formatting etc.
The Article detail probably wouldn't need the comments as it's essentially the meta-data about the Article whereas the Article view is the Article as you'd want to present it for reading.
I am a bit stuck, hoping for guidance. I have 2 tables, Header and Details. However, the details is a bit different than most, and allows for a way to dynamically store data.: Yes, I am aware that I can create a table storing the details in the standard fashion, but the nature of the app needs to be more dynamic on the database side. I also realize I will have to modify the DTOs for different incarnations of the app, but this model is what I need to accomplish.
public class Header
{
public int Id { get; set; }
public string HeaderName { get; set; }
public ICollection<Detail> Details { get; set; }
}
public class Detail
{
public int Id { get; set; }
public int HeaderId { get; set; }
public string FieldName { get; set; }
public string FieldProperty { get; set; }
}
I want to use the following DTOs:
public class DataForDisplayDto
{
public int Id { get; set; }
public string HeaderName { get; set; }
public string TaskToPerform { get; set; }
public string Location { get; set; }
}
public class DataForCreationDto
{
public string HeaderName { get; set; }
public string TaskToPerform { get; set; }
public string Location { get; set; }
}
The data would be stored in the details in this fashion:
{
"FieldName": "tasktoperform",
"FieldProperty": "Thing to Do"
},
{
"FieldName": "location",
"FieldProperty": "Over there"
}
I am trying to use the Automapper to make it so I can read and write to the database using the DTOs, but I think I may be trying something it can't do.
Is there an article or something that anyone knows about that can point me in the direction to go? Or even the right keywords to search online for it. Is it even possible?
I suppose if it is not possible, I will have to do things a bit more manually, which is the last option, I am just hoping to do this with Automapper.
Thanks!
How about deriving your DTO from a base class that uses reflection to generate a mapping, and cache that mapping.
This way your DTO need only inherit a base class.
There are loads of resources for this on Google but I can't fully understand what I need to do in my scenario:
I have this class:
public class CompanyLanguage : EntityBase
{
public int CompanyId { get; set; }
public int LanguageId { get; set; }
public bool IsDefault { get; set; }
public virtual Company Company { get; set; }
public virtual Language Language { get; set; }
}
Language is defined as:
public class Language:EntityBase
{
[Required]
[DisplayName("Language Code")]
public string LanguageCode { get; set; }
[Required]
[MaxLength(2, ErrorMessage ="2 characters maximum")]
[DisplayName("2 Char Language Code")]
public string LanguageCode2Char { get; set; }
[Required]
[DisplayName("Language Name")]
public string LanguageName { get; set; }
public virtual List<LabelLanguage> LabelLanguages { get; set; }
}
Running a Fortify Scan returns the issue below as a high priority:
(ASP.NET MVC Bad Practices: Optional Submodel With Required Property)
We can't run the fortify scan - it's being run by someone else, so I need to get the changes right so it doesn't come straight back.
All the resources I've looked at suggest that underposting attacks could be made - i.e. a null Language, even though Language has some required properties.
For me, this is a valid scenario - the required properties of Language are only required if Language isn't null.
So what am I supposed to do to resolve this? Do I make public int LanguageId { get; set; } required, or public virtual Language Language { get; set; } or both?
Or am I completely wrong an I have to do something else? As I say I can't test these as the software has to be sent away for the test or I'd be trying all sorts out.
To summarize our discussion from comments.
Create a view model which models only the information that is needed to satisfy the corresponding view.
populate view models in your controller action from your domain ef models
either project directly into view models using linq queries or Automapper.
Example view model for your question
public class CompanyLanguageEditViewModel
{
[DisplayName("Company")]
[Required]
public int CompanyId { get; set; }
[DisplayName("Language")]
[Required]
public int LanguageId { get; set; }
public bool IsDefault { get; set; }
public IEnumerable<SelectListItem> Companies{ get; set; }
public IEnumerable<SelectListItem> Languages { get; set; }
}
And in your view you can then use
#Html.DropDownListFor(x => x.CompanyId, Model.Companies);
and your label will be Country and you are only going to POST back what you need
Hi I have a situation in witch I have to create some custom validation attributes because the way my model is created.The model looks something like this:
public class EvaluationFormDataContract
{
public int StudentAssignmentInstanceId { get; set; }
public int EvaluationType { get; set; }
public List<CategoriesOnEvaluationDataContract> Categories { get; set; }
}
public class CategoriesOnEvaluationDataContract
{
public string Memo { get; set; }
public int CategoryId { get; set; }
public List<QuestionsOnEvalCategoryDataContract> Questions { get; set; }
// Fields needed for validation
public bool? HasMemo { get; set; }
public bool MemoIsMandatory { get; set; }
}
public class QuestionsOnEvalCategoryDataContract
{
public string Memo { get; set; }
public string Grade { get; set; }
public int QuestionId { get; set; }
// Fields needed for validation
public bool HasGrade { get; set; }
public bool HasMemo { get; set; }
public bool ShowOnlyMemo { get; set; }
}
As it can be seem the model is composed two levels deep.
And I will have to validate starting from the second level , where I will check if the model HasMemo and if MemoIsMandatory.
The third validation should be done at the 3rd level where I have to check if it HasGrade and HasMemo.
Normaly if it were up to me I would split this in three separate calls to the server but we are depending on an legacy project and for the moment I have to make this work.
The post action will be called via an ajax call and will have all this data into it.
Now my question is where should I add the validation attribute?
Should it be added at the top on Categories , making it directly responsible for all the levels of the model?
Or I should place it on each model and find a way to make the data binder aware of it? If so how can I do this?
You can do both. If you implement System.ComponentModel.DataAnnotations.IValidatableObject interface at the top-most level, you can do whatever you want with the properties in the entire graph and return the errors.
public class EvaluationFormDataContract : IValidatableObject
{
// All properties go here
public IEnumerable<ValidationResult> Validate(
ValidationContext validationContext)
{
if (// do what you want)
yield return new ValidationResult("message");
}
}
Or, you can apply attributes at the lower levels and automatically binding takes care of validating the properties in the graph. You don't need to do anything special.
I've read several articles about bunch of EF and DTO, and I need some clarification about using EF Code First and DTO in n-tier scenario with WCF.
Let's look a these classes:
public class Order
{
public int Id { get; set; }
public DateTime ShipDate { get; set; }
public ObservableCollection<OrderDetail> Details { get; private set; }
}
public class OrderDetail
{
public int Id { get; set; }
public int OrderId { get; set; }
public int ProductId { get; set; }
public decimal Quantity { get; set; }
}
When user want to edit existing order, my client application (WPF MVVM app) requests some DTO, which then being converted to Order instance. Then, user makes some changes in order through UI - e.g., changes ShipDate, removes two positions, modifies one, and adds one.
Now I want to deliver changes to the server. As far as I understand DTO concept, I need to construct some DTO type, containing info about changes has been made:
[DataContract]
public class UpdateOrderDTO
{
[DataMember]
public DateTime ShipDate { get; set; }
[DataMember]
public Collection<OrderDetail> NewDetails { get; private set; }
[DataMember]
public Collection<OrderDetail> ModifiedDetails { get; private set; }
[DataMember]
public Collection<OrderDetail> DeletedDetails { get; private set; }
}
But when, and where should I to create this DTO? I mean, I can't create it on submitting changes - there's no change tracking information in Order class.
Looks like, this object have to be created together with Order after it was requested for edition by user. This allows to track changes... Am I wrong?
Please note, that the question isn't about STEs. For some reasons, I don't want/can't use them in current project.
Thanks a lot for sharing your experience.