Load Partial Views from Database - asp.net

I'm having a requirement where the number of partial views could grow tomorrow and they could be a composition of any number of values and of any type. Well, yes, I can do this using partial views itself but the time I will add a new partial add, I will be required to recompile the application that I want to avoid. It would be very like a CMS where you just specify the fields and the form is generated on the fly based on fields and their type you specify.
Edit 1
Let's say for example you're building a survey application where you have multiple types of question and have associated partial views for every type. Now, if tomorrow you need to add one or more question types- how would you create a partial view dynamically on the fly for the new question type?
This is where the idea come from to store view definitions in an XML file or in Database so that the you can just add an entry for new partial view and you're good to display a new view for new question type without re-compiling > restarting your server.
Can we do something like that in ASP.NET MVC 5 using a data store (Any DB: SQL Server / MySQL or XML File / Flat File)? Any thoughts, pointers, tips are highly appreciated!
please correct if I'm incorrect.

Yes you can use a objectContainer that has multiple values:
Model of partial views:
public List<DynamicQuestion> dynamicQuestionList { get; set; }
public class DynamicQuestion
{
public string question{ get; set; }
public string ask{ get; set; }
}
wth that that you can get a List of DynamicQuestion so it's ok for you
in Db, you should have a table "question" that contains
id, question
that host all questions
and a table "ask" that has
id, idQuestion, response
that save all ask

Related

How to make changes in POCO file in Entity Framework so changes are retained

I am using Database First approach in Entity Framework. I have a table which contain one field called CustomerName and it is NOT NULL.
The generated POCO is given below.
public partial class Customers
{
public string CustomerName {get; set;}
}
I have two questions.
How can I make this a required field so my code would become like this (shown below). As you know POCO is automatically generated so after I do this and update model from database, all my code is removed.
public partial class Customers
{
[Required]
public string CustomerName {get; set;}
}
Second question is why EF automatically doesn't apply [Required] with this field when generating code? The field is NOT NULL in database so shouldn't this be done automatically without having to manually write [Required]?
Here's the answer if you're using EF6:
Notice that the generated Customers class is partial, we're going to leverage that. First, we'll need to create a new Customers partial class with the exact same name within the exact same namespace:
namespace WebApp.TheSameNamespaceAsTheGeneratedCustomersClass
{
public partial class Customers
{
}
}
Now both of these partials make up the same class it's just that the source code of this class is now split in different files, one of which is generated by the tool and one that you wrote by hand. The difference of course is that you can change the latter without it getting rewritten all the time.
Note that the namespace has to match but the folder that contains the class file doesn't.
Now we need to create the metadata class that contains all the necessary attributes and decorate our Customers partial with it, like so:
namespace WebApp.TheSameNamespaceAsTheGeneratedCustomersClass
{
[MetadataType(typeof(CustomersMetadata))] //decorating the entity with the metadata
public partial class Customers
{
}
public class CustomersMetadata //metadata class
{
[Required] //your data annotations
public string CustomerName { get; set; } //the property name has to match
}
}
and that's it.
Is it verbose? Yeah, but that decision was made when db first was chosen.
A word of caution:
If you're doing this to use entity classes as data models in MVC, generally speaking, that's considered a bad practice. The recommended way is to create separate model classes and map data from and to entities. There are some security reasons for that, which you should research before you make the final decision.
If you are using ef core then try adding --data-annotations flag in your scaffold command.
Please refer for more info: https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding?tabs=dotnet-core-cli#fluent-api-or-data-annotations
EF doesn't have any means of validating your data in your POCO classes when it generates sql. That is why it is recommended that we should have a corresponding model object layer (corresponding model classes for your entities) that your application can manipulate. You can use something like AutoMapper for mapping between models and entities. In this way you can modify your model classes without impacting your EF entities.

Is there a need for custom Domain Models when using LINQ?

I'm working on an MVC application using LINQ-SQL to connect to my SQL Server database.
Currently when fetching data, I'm passing the properties of my LINQ objects over to a Domain Model, which I'm then creating properties of in my View Models.
For example my View Model might have the following properties:
public Models.UserModel user { get; set; }
public List<Models.CountryModel> countries { get; set; }
My Domain Models have exactly the same properties as my LINQ objects, and I copy these properties over like:
Models.UserModel user = new Models.UserModel();
user.Username = User.Username;
user.FirstName = User.FirstName;
user.LastName = User.LastName;
Where user is my Models.UserModel object, and User is my LINQ object mapped from the User database table.
As my Domain Model is exactly the same as my LINQ object, is there any advantage for me transferring this data over to a Domain Model, or would it be okay for me to just use LINQ objects in my View Model such as:
public User user { get; set; }
public List<Country> countries { get; set; }
What are the advantages of using a Domain Model? Is this purely to loosely couple with the database LINQ objects?
If there are advantages to using Domain Models, how would be best to structure these within my MVC application?
Should they be split off entirely at the "Models" folder level (for example a sub-folder "DomainModels" and "ViewModels") or coincide (such as "UserEditViewModel.cs" and "UserDomainModel.cs").
As my Domain Model is exactly the same as my LINQ object, is there any
advantage for me transferring this data over to a Domain Model, or
would it be okay for me to just use LINQ objects in my View Model such
as:
You could reference domain models in your view models in case they are exactly the same. I don't see any benefit of duplicating this logic except that in the real world they are never the same. You always have some view specific things such as validation or even display labels. The advantage of having pure view models is that your application is no longer tied to your database structure. You could easily flip/flop data access technologies without modifying the UI part. I find it more maintainable to have this clear separation and always tend to make it in my applications.

Entity Framework - Including tables not mapped in data model?

I think this question is probably fairly simple, but I've been searching around and haven't been able to find what I'm looking for.
My team and I are adding a new module to our existing web application. We already have an existing data model which is hooked up to our sql db, and it's pretty huge... So for the new module I created a new EF data model directly from our database with the new tables for the new module. These new tables reference some of our existing tables via foreign keys, but when i add those tables, all of the foreign keys need to be mapped for that table, and their tables, and their tables... and it seems like a huge mess.
My question is, instead of adding the old tables to the data model, since I'm only referencing the ID's of our existing tables for Foreign key purposes can I just do a .Includes("old table") somewhere in the DataContext class or should I go back and add those tables to the model and remove all of their relationships? Or maybe some other method I'm not even aware of?
Sorry for the lack of code, this is more of a logic issue rather than a specific syntax issue.
Simple answer is no. You cannot include entity which is not part of your model (= is not mapped in your EDMX used by your current context).
More complex answer is: in some very special case you can but it requires big changes to your development process and the way how you work with EF and EDMX. Are you ready to maintain all EDMX files manually as XML? In such case EF offers a way to reference whole conceptual model in another one and use one way relations from the new model to the old model. It is a cheat because you will have multiple conceptual models (CSDL) but single mapping file (MSL), single storage description (SSDL) and single context using all of them. Check this article for an example.
I'm not aware that you can use Include to reference tables outside of the EF diagram. To start working with EF then you only need to include a portion of the database in - if your first project is working with a discrete functional area which it probably would be. This might get round the alarming mess when you import and entire legacy database. It scared me when I tried to do it.
In our similar situation - a big legacy system that used stored procedures, we only added the tables that we were directly working at that time. Later on you can always add in additional tables as and when you require them. Don't worry about foreign keys in the EF diagram that are referencing tables that aren't included. Entity Framework happily copes with this.
It does mean running two business layers though one for entity framework and one for the old style data access. Not a problem for us though. In fact from what I've read about legacy system programming it's probably the way to go - you have a business layer with your scruffy old stuff and a business layer with your sparkly new stuff. Keep moving from old to the new until one day the old business layer evaporates into nothing.
You have to use [Include()] over the member.
For example:
// This class allows you to attach custom attributes to properties
// of the Frame class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class FrameMetadata
{
// Metadata classes are not meant to be instantiated.
private FrameMetadata()
{
}
[Include()]
public EntityCollection<EventFrame> EventFrames { get; set; }
public Nullable<int> Height { get; set; }
public Guid ID { get; set; }
public Layout Layout { get; set; }
public Nullable<Guid> LayoutID { get; set; }
public Nullable<int> Left { get; set; }
public string Name { get; set; }
public Nullable<int> Top { get; set; }
public Nullable<int> Width { get; set; }
}
}
And the LINQ should have
.Includes("BaseTable.IncludedTable")
syntax.
And for the entities which are not part of your model you have to create some view classes.

XML Serializiation migration to MySql

I have an ASP.NET project that uses XML Serialization for the main operation for saving data. This project was to stay small relative to size of data. However, the amount of data has ballooned as it always will and now I'm consider moving to a SQL based alternative for managing the data.
For now I have multiple objects defined that are simply storage classes for saving my data for the project to work.
public class Customer
{
public Customer() { }
public string Name { get; set; }
public string PhoneNumber { get; set; }
}
public class Order
{
public Order() { }
public int ID { get; set; }
public Date OrderDate { get; set; }
public string Product { get; set; }
}
Something along these lines although not so rudimentary. Migrating to SQL seems to be a no-brainer and I've landed on using MySql because of the free availability of the service. What I'm running into is that the only way I can see to do this now is to have a solution where there is a storage class, Order, and a class built to Load/Save the data, OrderIO.
The project relies heavily on using List<> to populate the data fields on the page. I'm not using any built-in .NET controls such as DataGrid to assist in displaying the data. Simple TextBox or ComboBox controls that are populated on Page_Load.
I'm aware it would make better sense to pick a way in which the data fields could bind to the SQL through a Repeater but I'm not looking at a full redesign, just a difference on the infrastructure to manage the data.
I would like to be able to create a class that can return an object similar to what I'm dealing with now, such as List<>, from the SQL statements I'm executing. I'm having some trouble getting started on the best method of approach.
Any suggestions on how best to Load/Save this data using SQL or some tutorials on ideas using the .NET framework would be helpful. This is quite a generalized question but I'm open to most ideas. Thanks.
What you need is a Data Access Layer (DAL) that takes care of running the SQL code and returning the required data in the List<> format that you require. I would definitely recommend you read the two series of articles by Imar Spaanjar on Building a N-Layer Application. Note that there are two sets of series, but I linked to the second set, because it contains links to the first one.
Also, it might be beneficial to know that Sql Server 2008 R2 express edition is free to use, but has a limit of 10 GB per database. I am not saying that you shouldn't use MySQL, but just wanted to inform you in case you didn't know that there is a free edition of Sql Server available.

ASP.NET MVC - Complex Objects and Forms

So let's say we have a domain object such as the following
public class Person
{
public string Name { get; set; }
public IList<PhoneNumber> PhoneNumbers {get; set; }
public IList<Address> Addresses { get; set; }
}
The Person is not valid until a name, phone numbers, and addresses have been entered. How do you guys handle this using ASP.NET MVC and forms...
I was thinking you could serialze the Person to session and have multiple views for editing Name, adding phone numbers, adding addresses - the controller actions would modify the person in the session and a final Save action would push to database.
I don't really like having multiple views and using the session. Another option would be to have a single very complex form that could have "dynamic" sections of elements for adding/removing phone numbers, addresses within the browser prior to posting to the save action.
What is everyone doing with complex objects and editing via forms?
Thanks!
I would usually use the "dynamic section" route.
However, I would not make your validation so strict that the user is unable to save work in progress. A list of phone numbers, addresses, etc., can take quite a while to enter. It is beneficial to the end-user to be able to save their work from time to time in case they lose Internet connectivity or something. It's probably a good idea to save the records automatically via AJAX from time to time if your data entry form is quite large. (Like Gmail.) Therefore, your model should allow them to save incomplete work from time to time, and run the whole validation only when they say they are "done."

Resources