Master Detail CRUD Operations Using EF And ASPnet MVC 3 In C

12/07 0 By bronell

Master Detail CRUD Operations Using EF And ASP.NET MVC 3 In C#

CRUD operations are the basic operations that allow you to create, read, update and delete data from a database. In this article, you will learn how to perform master detail CRUD operations using Entity Framework (EF) and ASP.NET MVC 3 in C#. Master detail CRUD operations are useful when you have a one-to-many relationship between two entities, such as a customer and their orders.

What is Entity Framework?

Entity Framework (EF) is an object-relational mapper (ORM) that enables you to work with relational data using domain-specific objects. EF eliminates the need for writing most of the data access code by generating it for you. EF also provides various features such as lazy loading, change tracking, migrations, and more.

What is ASP.NET MVC 3?

ASP.NET MVC 3 is a web development framework that follows the Model-View-Controller (MVC) pattern. MVC separates the application into three components: the model, which represents the data and business logic; the view, which displays the user interface; and the controller, which handles the user requests and interactions. ASP.NET MVC 3 provides many benefits such as testability, extensibility, and control over the HTML output.

How to Perform Master Detail CRUD Operations Using EF And ASP.NET MVC 3 In C#?

To perform master detail CRUD operations using EF and ASP.NET MVC 3 in C#, you need to follow these steps:

  1. Create a database and define the tables and relationships.
  2. Create an EF model from the database using the Database First approach.
  3. Create an ASP.NET MVC 3 project and add the EF model as a reference.
  4. Create a controller and views for the master entity using scaffolding.
  5. Create a partial view for the detail entity and render it in the master view.
  6. Add code to the controller and views to handle the CRUD operations for the detail entity.

In this article, we will use an example of a customer and their orders as the master detail entities. The customer table has fields such as CustomerId, Name, Email, Phone, etc. The order table has fields such as OrderId, CustomerId, Date, Total, etc. The customer table has a one-to-many relationship with the order table.

Create a Database and Define the Tables and Relationships

For this example, we will use SQL Server as the database. You can use any database management tool such as SQL Server Management Studio (SSMS) or Visual Studio to create the database and the tables. The following script shows the SQL commands to create the customer and order tables and define the foreign key relationship between them:


CREATE DATABASE MasterDetailDemo;
GO

USE MasterDetailDemo;
GO

CREATE TABLE Customer (
CustomerId INT IDENTITY(1,1) PRIMARY KEY,
Name NVARCHAR(50) NOT NULL,
Email NVARCHAR(50) NOT NULL,
Phone NVARCHAR(15) NULL
);
GO

CREATE TABLE [Order] (
OrderId INT IDENTITY(1,1) PRIMARY KEY,
CustomerId INT NOT NULL,
[Date] DATE NOT NULL,
Total DECIMAL(18,2) NOT NULL,
CONSTRAINT FK_Order_Customer FOREIGN KEY (CustomerId) REFERENCES Customer(CustomerId)
);
GO

Create an EF Model from the Database Using the Database First Approach

The Database First approach is one of the ways to create an EF model from an existing database. In this approach, you use a wizard in Visual Studio to generate the EF model based on the database schema. The EF model consists of entity classes that represent the tables and a DbContext class that represents the database connection and operations. The following steps show how to create an EF model from the database using the Database First approach:

  1. In Visual Studio, create a new Class Library project and name it MasterDetailDemo.Model.
  2. Right-click on the project and select Add > New Item.
  3. Select Data from the left pane and choose ADO.NET Entity Data Model from the right pane. Name it MasterDetailDemoModel.edmx and click Add.
  4. In the Entity Data Model Wizard, select Generate from database and click Next.
  5. Click New Connection to create a connection to the database. Enter the server name, authentication mode, and database name. Test the connection and click OK.
  6. Click Next and select the tables you want to include in the model. In this case, select both Customer and Order tables. Click Finish.
  7. The EF model will be generated and displayed in the designer. You can see the entity classes and their properties that correspond to the tables and columns. You can also see the association that represents the relationship between the entities.

Create an ASP.NET MVC 3 Project and Add the EF Model as a Reference

Next, we need to create an ASP.NET MVC 3 project that will use the EF model to perform the CRUD operations. The following steps show how to create an ASP.NET MVC 3 project and add the EF model as a reference:

  1. In Visual Studio, create a new ASP.NET MVC 3 Web Application project and name it MasterDetailDemo.Web.
  2. Right-click on the project and select Add > Reference.
  3. Browse to the MasterDetailDemo.Model project and select it. Click OK.
  4. Right-click on the References folder in the MasterDetailDemo.Web project and select Add > Service Reference.
  5. Click Discover and select MasterDetailDemoModel from the list. Name it MasterDetailService and click OK.
  6. This will create a service reference that will allow the web project to access the EF model.

Create a Controller and Views for the Master Entity Using Scaffolding

Now, we can use the scaffolding feature of ASP.NET MVC 3 to generate a controller and views for the master entity, which is Customer in this case. The scaffolding feature will create a controller class with methods for performing CRUD operations and corresponding views with forms and tables. The following steps show how to use scaffolding to create a controller and views for the Customer entity:

  1. Right-click on the Controllers folder in the MasterDetailDemo.Web project and select Add > Controller.
  2. Name the controller CustomerController and select MasterDetailService.Customer as the model class. Select MasterDetailService.MasterDetailDemoModelContainer as the data context class. Check the Generate views checkbox and select Razor as the view engine. Click Add.
  3. This will create a CustomerController class with methods for Index, Details, Create, Edit, and Delete actions. It will also create corresponding views in the Views/Customer folder.
  4. Run the application and navigate to /Customer. You should see a list of customers from the database. You can also click on Create New, Edit, Details, or Delete links to perform CRUD operations on customers.

Create a Partial View for the Detail Entity and Render It in the Master View

The next step is to create a partial view for the detail entity, which is Order in this case. A partial view is a view that can be rendered inside another view. We will create a partial view that will display the orders for a selected customer and allow the user to add, edit, or delete orders. The following steps show how to create a partial view for the Order entity and render it in the Customer view:

  1. Right-click on the Views/Shared folder in the MasterDetailDemo.Web project and select Add > View.
  2. Name the view _Order and select MasterDetailService.Order as the model class. Check the Create as a partial view checkbox and select Razor as the view engine. Click Add.
  3. This will create a partial view named _Order.cshtml in the Views/Shared folder.
  4. Open the _Order.cshtml file and replace the code with the following:


@model IEnumerable

Orders

@Html.ActionLink("Create New", "Create", "Order", new { customerId = ViewBag.CustomerId }, null)

@foreach (var item in Model) {

}

OrderId Date Total
@Html.DisplayFor(modelItem => item.OrderId) @Html.DisplayFor(modelItem => item.Date) @Html.DisplayFor(modelItem => item.Total) @Html.ActionLink("Edit", "Edit", "Order", new { id=item.OrderId }, null) |
@Html.ActionLink("Details", "Details", "Order", new { id=item.OrderId }, null) |
@Html.ActionLink("Delete", "Delete", "Order", new { id=item.OrderId }, null)

  1. This code will display a table of orders for a given customer and provide links to perform CRUD operations on orders.
  2. Open the Views/Customer/Details.cshtml file and add the following code at the end of the file:


@{ Html.RenderAction("Index", "Order", new { customerId = Model.CustomerId }); }

  1. This code will render the _Order partial view inside the Customer details view by calling the Index action of the Order controller and passing the customer id as a parameter.
  2. Run the application and navigate to /Customer/Details/1. You should see the details of customer 1 and a list of their orders. You can also click on Create New, Edit, Details, or Delete links to perform CRUD operations on orders.

Add Code to the Controller and Views to Handle the CRUD Operations for the Detail Entity

The final step is to add code to the Order controller and views to handle the CRUD operations for the detail entity. The Order controller and views were not generated by scaffolding, so we need to create them manually. The following steps show how to add code to the Order controller and views to handle the CRUD operations for the detail entity:

  1. Right-click on the Controllers folder in the MasterDetailDemo.Web project and select Add > Controller.
  2. Name the controller OrderController and leave the other options as default. Click Add.
  3. This will create an empty OrderController class in the Controllers folder.
  4. Open the OrderController.cs file and add the following code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MasterDetailDemo.Web.Controllers
{
public class OrderController : Controller
{
// Create a service reference object
private MasterDetailService.MasterDetailDemoModelContainer service = new MasterDetailService.MasterDetailDemoModelContainer();

// GET: /Order/Index/5
public ActionResult Index(int customerId)
{
// Get the orders for a given customer
var orders = service.GetOrdersByCustomer(customerId);

// Set the customer id as a view bag property
ViewBag.CustomerId = customerId;

// Return the orders as a model
return PartialView("_Order", orders);
}

// GET: /Order/Details/5
public ActionResult Details(int id)
{
// Get the order by id
var order = service.GetOrderById(id);

// Return the order as a model
return View(order);
}

// GET: /Order/Create/5
public ActionResult Create(int customerId)
{
// Create a new order object with the customer id
var order = new MasterDetailService.Order { CustomerId = customerId };

// Return the order as a model
return View(order);
}

// POST: /Order/Create/5
[HttpPost]
public ActionResult Create(int customerId, MasterDetailService.Order order)
{
try
{
// Add the order to the service
service.AddOrder(order);

// Save the changes to the service
service.SaveChanges();

// Redirect to the customer details page
return RedirectToAction("Details", "Customer", new { id = customerId });
}
catch
{
// Return the view with the model in case of error
return View(order);
}
}

// GET: /Order/Edit/5
public ActionResult Edit(int id)
{
// Get the order by id
var order = service.GetOrderById(id);

// Return the order as a model
return View(order);
}

// POST: /Order/Edit/5
[HttpPost]
public ActionResult Edit(int id, MasterDetailService.Order order)
{
try
{
// Update the order in the service
service.UpdateOrder(order);

// Save the changes to the service
service.SaveChanges();

// Redirect to the customer details page
return RedirectToAction("Details", "Customer", new { id = order.CustomerId });
}
catch
{
// Return the view with the model in case of error
return View(order);
}
}

// GET: /Order/Delete/5
public ActionResult Delete(int id)
{
// Get the order by id
var order = service.GetOrderById(id);

// Return the order as a model
return View(order);
}

// POST: /Order/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// Get the order by id
var order = service.GetOrderById(id);

// Delete the order from the service
service.DeleteOrder(order);

// Save the changes to the service
service.SaveChanges();

// Redirect to the customer details page
return RedirectToAction("Details", "Customer", new { id = order.CustomerId });
}
catch
{
// Return to the same view in case of error
return View();
}
}
}
}

  1. This code will create methods for performing CRUD operations on orders using the service reference object. It will also redirect to or render partial views based on the actions.
  2. Right-click on

    Conclusion

    In this article, you learned how to perform master detail CRUD operations using EF and ASP.NET MVC 3 in C#. You learned how to create a database and define the tables and relationships, how to create an EF model from the database using the Database First approach, how to create an ASP.NET MVC 3 project and add the EF model as a reference, how to create a controller and views for the master entity using scaffolding, how to create a partial view for the detail entity and render it in the master view, and how to add code to the controller and views to handle the CRUD operations for the detail entity. You also saw an example of a customer and their orders as the master detail entities. By following these steps, you can create your own master detail CRUD applications using EF and ASP.NET MVC 3 in C#.

    https://github.com/luelimerto/langchain/blob/master/tests/The%20Bible%20Full%20Movie%20Tagalog%20Version%202014%20ABS%20CBN%20Watch%20the%20Epic%20Story%20of%20Gods%20Love.md
    https://github.com/3niedoXdianu/Angular-Full-Stack/blob/master/.github/BMW%20DIS%20V44%20V57%20SSS%20V32%20amp%20TIS%20V8%20GT1%20INPA%20EDIABAS%20DIAGNOSTIC%20SOFTWARE%20How%20to%20Install%20Use%20and%20Update%20It%20on%20Your%20PC%20or%20Laptop.md
    https://github.com/racoeZtincpo/botui/blob/main/packages/Crack%20Optimik%202.36c.rar%201%20The%20Best%20Software%20for%20Cutting%20Optimization%20and%20Material%20Saving.md
    https://github.com/gratinQdispde/Metro-UI-CSS/blob/4.5.2/tests/data/ATIR.STRAP.2011.BEAMD.2010%2064%20bit%20Supports%20Various%20National%20Design%20Codes%20and%20Standards.md
    https://github.com/togeerta/Price-Tracking-Web-Scraper/blob/main/scheduler/Windows%20XP%20Pilitos%20LiveCD%20Spanish%20full%20version%20Un%20sistema%20operativo%20ligero%20y%20portable.md
    https://github.com/unolWciaso/openface/blob/master/tests/Epson%20LQ%202190%20Service%20Manual.rar%20A%20Complete%20Guide%20to%20Troubleshooting%20and%20Maintenance.md
    https://github.com/confgilPculmi/premake-core/blob/master/contrib/lua/Autodesk%20Revit%202020%20Crack%20(Product%20Key%20Keygen)%20Torrent%20[UPDATED].md
    https://github.com/9gnosobtinchi/Anima/blob/main/scripts/Infamous%202%20Pc%20Download%2018%20What%20to%20Expect%20from%20the%20Sequel%20of%20the%20Hit%20Game.md
    https://github.com/0grasarQdempbo/anything-llm/blob/master/docker/Flippingbook%20publisher%202.2.8%20crack%20How%20to%20create%20stunning%20digital%20publications.md
    https://github.com/7ferlitiszu/shell_gpt/blob/main/sgpt/PS2%20PFS%20Explorer%200.7.0.26E.rar%20The%20Ultimate%20Software%20for%20PS2%20Memory%20Card%20and%20Hard%20Disk.md

    86646a7979

загрузка...