You are currently offline, waiting for your internet to reconnect

CRUD using Entity Framework in .NET Framework 5.0 - (Create)

About Author:

MVP This article is provided by MVP Ming Man. Microsoft is so thankful that MVPs who proactively share their professional experience with other users. The article would be posted on MVP's website or blog later.
Summary
Entity Framework (EF) is an object-relational mapper (ORM) that enables .NET developers to work with relational data using domain-specific object models. It eliminates the need for most of the data-access code that developers usually need to write.

This article describes 3 steps to insert a row into database table using Entity Framework.
  1. Get latest Entity Framework
  2. Create Entity Model
  3. Insert row to database through Entity Framework
Get latest Entity Framework
  1. Create a console project or a web project in visual studio.
  2. Right click References then select Manage NuGet Packages…


    Figure 1. Manage NuGet Package

  3. Type Entity Framework on the task bar at the up right hand corner to search latest Entity Framework from NuGet server. You can see Entity Framework 5.0 listed at very top of the list.


    Figure 2. Search package in NuGet

  4. Click the Install button to install Entity Framework 5 for the project. Click I Accept when the License Acceptance window pops up.


    Figure 3. Entity Framework license acceptance
  5. You can see the small green tick indicated that the Entity Framework has installed successfully.


    Figure 4. Entity Framework installation completed
  6. You can use the Properties window to verify the version of the Entity Framework after the completion of Entity Framework installation.


    Figure 5. Entity Framework verification in Properties Window
Create Entity Model
  1. Choose PROJECT -> Add New Item… from pull down menu to add an Entity Model. Type a name for your entity model. Click Add.
  2. Choose Data category then select ADO.NET Entity Data Model. Type a name for the Entity Model.


    Figure 6. Add ADO.NET Entity Data Model
  3. There are two options to obtain Entity Data Model. You can either General from database or start with Empty model. In this article we will use the existing database, choose General from database. Click Next to continue.


    Figure 7. Choose a method to generate model
  4. You can choose your existing data connect or create new data connect. We will create new data connection here. Click New Connection to select a database.


    Figure 8. Choose or create new connection
  5. Once the connection is set then you will have an option to save the connection string to App.config (it will be Web.config if you have a web project). Click Next.


    Figure 9. Connection creation completed
  6. Select object from the database. You can select Tables, Views or Stored Procedures for example select all the tables in the database except the sysdiagrams (MS SQL generated table). By default, the three options, Pluralize or singularize generated object names, Include foreign key columns in the model and Import selected stored procedures and functions into the entity model are selected.


    Figure 10. Choose database object
  7. The entity model will be created as an edmx file in the project. When you open the entity model then you are able to see the model and the relationship between models.


    Figure 11. Entity Model

Insert row to database through Entity Framework
  1. 1. Declare the data context. Create an instance of the Entity Model object.

    northwindEntities ctx = new northwindEntities();
  2. Create an instance for Entity object with data initialization.

    Product product = new Product()
    {
    CategoryID = 1,
    ProductName = "Drink",
    SupplierID = 1,
    QuantityPerUnit = "10 boxes x 20 bags",
    UnitPrice = 1,
    UnitsInStock = 25,
    UnitsOnOrder = 10,
    ReorderLevel = 2,
    Discontinued = false
    };

  3. Add the entity to the data context. This is still in memory and not physical store in any database yet.

    ctx.Products.Add(product);

  4. Save the data context, this will also save the data into the data source. The data source in this example is the northwind database in Microsoft SQL Server.

    ctx.SaveChanges();

    The complete code is like the one below.

    northwindEntities ctx = new northwindEntities();

    Product product = new Product()
    {
    CategoryID = 1,
    ProductName = "Drink",
    SupplierID = 1,
    QuantityPerUnit = "10 boxes x 20 bags",
    UnitPrice = 1,
    UnitsInStock = 25,
    UnitsOnOrder = 10,
    ReorderLevel = 2,
    Discontinued = false
    };

    ctx.Products.Add(product);
    ctx.SaveChanges();



Community Solutions Content Disclaimer

MICROSOFT CORPORATION AND/OR ITS RESPECTIVE SUPPLIERS MAKE NO REPRESENTATIONS ABOUT THE SUITABILITY, RELIABILITY, OR ACCURACY OF THE INFORMATION AND RELATED GRAPHICS CONTAINED HEREIN. ALL SUCH INFORMATION AND RELATED GRAPHICS ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO THIS INFORMATION AND RELATED GRAPHICS, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, WORKMANLIKE EFFORT, TITLE AND NON-INFRINGEMENT. YOU SPECIFICALLY AGREE THAT IN NO EVENT SHALL MICROSOFT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL, CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF USE, DATA OR PROFITS, ARISING OUT OF OR IN ANY WAY CONNECTED WITH THE USE OF OR INABILITY TO USE THE INFORMATION AND RELATED GRAPHICS CONTAINED HEREIN, WHETHER BASED ON CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY OR OTHERWISE, EVEN IF MICROSOFT OR ANY OF ITS SUPPLIERS HAS BEEN ADVISED OF THE POSSIBILITY OF DAMAGES.
Properties

Article ID: 2780458 - Last Review: 09/25/2013 11:11:00 - Revision: 2.1

  • Microsoft .NET Framework 4.5
  • kbstepbystep kbmvp kbcommunity KB2780458
Feedback
rosoft.com/ms.js"> type="text/javascript" src="https://c.microsoft.com/ms.js" '="">