EagerToLearn
EagerToLearn

Reputation: 95

What is the best way to write data via MVC into database?

I am working on a homework project using MVC with EF Core. I am looking for the best way to write data into the database. (I am beginner) There are two tables. Predbilježba(Enrollment) and Seminari(Seminars)

public class Predbilježba
{
    [Key]
    public int PredbilježbeID { get; set; }
    public string Ime { get; set; }
    public string Prezime { get; set; }
    public string Adresa { get; set; }
    public string Email { get; set; }
    public string Telefon { get; set; }
    public bool Status { get; set; }

    [DataType(DataType.Date)]
    public DateTime DatumUpisa { get; set; }  
    public int SeminarID { get; set; }
    public Seminar Seminar { get; set; }
}

public class Seminar
{
    public int SeminarID { get; set; }
    public string Naziv { get; set; }
    public string Opis { get; set; }

    [DataType(DataType.Date)]
    public DateTime Datum { get; set; }
    public bool Popunjen { get; set; }
    public ICollection<Predbilježba> Predbilježba { get; set; }
}

I need to insert a sort of Enrollment (Named: Predbilježba) into the database. Enrollment is connected to a table called Seminars (Named: Seminari).

So when a person is "enrolling" into a "seminar", he/she needs to insert basic data into form (name, phone number, etc.) and they need to choose a "seminar" from a list of given seminars which are in "Seminar" table.

So when they click "Save", their basic data is written into Predbilježba / (eng. Enrollment)" along with chosen "seminar"

So I already have controllers for these 2 models, and appropriate views to create, edit, and so on..

My question is: Do I create a separate controller/model/view to insert data into tables? Can someone give me some example of how it is done?

To clarify further, I need to make user side page where user can "enroll" to "seminar" by writing name, last name, etc.. and by choosing the desired seminar. For now I have functional database, Identity (which will be used later in project), controllers of both models, and appropriate views where I can edit Prebilježbe(eng. Enrollments) and Seminars.

Images of page follow: Image1 Image2 Image3 Image4

So when user clicks Upiši se (eng. enroll) as shown in image number 3. , that selected Seminar, along with basic info that opens after the click (image 4 ) needs to be written into database "Predbilježbe" (eng Enrollments)

This "Upis" page would be a user input page, and "Seminari" and "Predbilježbe" would be admin pages..

Upvotes: 4

Views: 220

Answers (4)

Mohammed Noureldin
Mohammed Noureldin

Reputation: 16806

If I understand your question correctly, you are asking about good architectural design. Aren't you? (if not please let me know to edit the answer).

You have many architectural choices and possibilities. The easiest one for you to start with is the Service-Repository architectural pattern. I would omit the Repository word here because EF is already (in my opinion) a Repository pattern implementation (at least partially).

So to keep it simple, you would like to start with Service architectural pattern. Which is about creating a class, which injects the DbContext in its construction (let's name it PredbilježbaService). And in this class, you handle all operations of your logic (including database EF queries).

Then you inject this class to your controller and call the required functions from that service class (which deals with the database) in your controller.

The same process can be applied to the other entity Seminar.

P.S. by injecting I mean using any IoC design pattern (in ASP.Net Core, dependency injection is already built-in).

So after these brief words, to answer your question directly, yes, a good software design would be by creating a separate class which handles database operations (adding rows, editing rows, etc.)

Upvotes: 3

Jeroen
Jeroen

Reputation: 1262

It all depends on what your application is supposed to do.

If this is nothing more than a few views around a few tables, then it is perfectly fine to save these objects directly from the controller. The best design is usually the simplest one and there is no need to overcomplicate things with layers, architectural patterns and so on. These are relevant when the size of the project is much larger than in your case.

Good design is all about communication. If someone else is supposed to maintain your project, will it be clear to them where to find the functionality?

I would expect two controllers: one for seminars (called SeminarController) and one for enrollments (called EnrollmentController). These will have methods for viewing, inserting, modifying and deleting data. I would be able to extend your project easily because I know where (and how) to find the code. So your suggestion seems like a good fit.


Response to comment

In the list of seminars has a link pointing to the screen where someone can register for a seminar. That action needs to know which seminar has been selected. The way to do it is to pass the id of the seminar with the request, e.g. /Enrollment/Register/{seminar id}. This results in a GET-request. The form in the enrollment view will POST the inputted data back to the controller.

In the EnrollmentController you would have something like this:

private readonly MyDbContext context;

// Constructor and other methods omitted

[HttpGet]
public ActionResult Register(int seminarId)
{
    var seminar = context.Seminars.Single(x => x.Id == seminarId);
    return View(seminar);
}

[HttpPost]
public ActionResult Register(Enrollment enrollment)
{
    context.Enrollment.Add(enrollment);
    return RedirectToAction("index", "Seminar");
}

Depending on the requirements, you might need to insert some validation etc.

Upvotes: 1

Dblaze47
Dblaze47

Reputation: 868

You need to study about software architectures a bit to clarify this. Try reading about Layered Architecture for basic structures, and I am assuming you already understand how the MVC architecture works. These will clarify where to perform which task. One of my favorites is the Onion architecture. So basically when you implement an architecture in your code, it becomes much more easy to read, control and track all activities performed within the code.

At the simplest, it is better to split the tasks as below:

1. You define your model classes 
2. You create a database class/layer, where you will implement the logic to perform data base queries into your database with respect to the models and return the formatted data (This is where you perform the EF core queries).
3. You create your controllers, where you handle tasks by sending appropriate requests to the database layer and fetch the formatted data.
4. You create your views based on the expected model, and setup the controllers to send the formatted model data to the appropriate view. 

A good place to start is here: Tutorial on EF core with MVC

Upvotes: 0

gowiththestackflow
gowiththestackflow

Reputation: 36

The best way to achieve this in MVC is tu use the nuget package EntityFrameworkCore

Here is a step by step documentation: https://learn.microsoft.com/en-us/ef/core/get-started/

For any further questions, feel free to ask.

Upvotes: -1

Related Questions