Introduction

This article introduces Entity Framework to absolute beginners. The article is meant for developers who are primarily using ADO.NET to write their data access layers.  Many experienced developers will find this article very basic but since the article is written from the perspective of beginners, I've tried to keep things simple.

Background

ADO.NET is a very strong framework for data access. ADO.NET has been around since many years and there are a lot of systems running over ADO.NET. Developers who are  totally oblivious to the concept of ORMs will probably be asking "What is Entity Framework? What are the benefits of using it and is it an alternative to ADO.NET?"

Well, to answer the first question about what is Entity Framework, Entity Framework is an Object Relational Mapper (ORM). It basically generates business objects  and entities according to the database tables and provides the mechanism for:

  1. Performing basic CRUD (Create, Read, Update, Delete) operations.
  2. Easily managing "1 to 1", "1 to many", and "many to many" relationships.
  3. Ability to have inheritance relationships between entities.

and to answer the second question, the benefits are:

  1. We can have all data access logic written in higher level languages.
  2. The conceptual model can be represented in a better way by using relationships among entities.
  3. The underlying data store can be replaced without much overhead since all data access logic is present at a higher level.

and finally, the last question that whether it is an alternative to ADO.NET, the answer would be "yes and no". Yes because the developer will not be writing ADO.NET  methods and classes for performing data operations and no because this model is actually written on top of ADO.NET, meaning under this framework, we are still  using ADO.NET. So let us look at the architecture of Entity Framework (diagram taken from MSDN):

Using the code

Let's try to understand the ease of use that Entity Framework provides by performing simple CRUD operations. Once we look at the code and how effortlessly and  efficiently we can do these operations, the benefits of Entity Framework will become quite obvious.

Creating the database

Let's have a simple database with one table. Let's create a simple table for Contacts and we will perform CRUD operations on this table.

Adding the Entity Model to the Website

Once we have the database ready, we can add the entity model to our website. We can do this by adding an ADO.NET Entity Data Model to the website.

Once we select to add this data model to our website, we will have to select the approach we want to take for our Model's contents.

What this selection means is that we can either choose to generate the entity model from an existing database schema or we can design the entity model here and then later  hook it up to the database. Since we already have the database ready, we will use the first option.  Once the Model is generated, the Entity for each table is generated. The generated entity for our contact table is:

Also, the classes for performing database operations are also created. We just need to know how to use these classes to perform database operations.

Insert operation

Let us create a simple page to perform an insert operation.

Now once the user chooses to insert the values into the database, the actual data operation can be performed by using the AddObject method of the Model class entity  collection. The following code snippet show how to perform the insert.

Contact con = new Contact();
con.fname = TextBox1.Text;
con.lname = TextBox2.Text;
con.phone = TextBox3.Text; ContactsDb db = new ContactsDb();
db.Contacts.AddObject(con);
db.SaveChanges();

This will insert the record into the table. You can notice the simplicity and efficiency of the code we wrote to perform the insertion.

Reading all the records

There are scenarios when we want to read all records. Let's say we are making a page that will display all the contact information in a single page.

We can retrieve the collection of Entities using the Model object to achieve this. The code snippet below will show how that can be done.

ContactsDb db = new ContactsDb();
Repeater1.DataSource = db.Contacts;
Repeater1.DataBind();

Selecting a specific record

If we want to select a specific record from the table, we can use the SingleOrDefault method on the Model's entities collection. Let's say we want the functionality  of updating/deleting a record on a single page then we will first have to select the record based on the ID, then update/delete the selected record.

Selection of any particular record (Contact) based on ID can be done as:

int idToupdate = Convert.ToInt32(Request.QueryString["id"].ToString());
ContactsDb db = new ContactsDb();
Contact con = db.Contacts.SingleOrDefault(p => p.id == idToupdate);

Once this code is executed, the Contact object will contain the required values.

Updating the record

If we want to update a record, then a simple update operation can be performed as:

int idToupdate = Convert.ToInt32(Request.QueryString["id"].ToString());
ContactsDb db = new ContactsDb();
Contact con = db.Contacts.SingleOrDefault(p => p.id == idToupdate); con.phone = TextBox1.Text;
db.SaveChanges();

Once this code executes, the value of phone number will be updated by a new value which is retrieved from TextBox1.

Deleting a record

If we want to delete a particular record then we can perform a delete operation by using the DeleteObject function. The following code snippet demonstrates the same:

//delete this contact
int idToupdate = Convert.ToInt32(Request.QueryString["id"].ToString());
ContactsDb db = new ContactsDb();
Contact con = db.Contacts.SingleOrDefault(p => p.id == idToupdate); db.Contacts.DeleteObject(con);
db.SaveChanges();

Now that we have the basic CRUD operations performed on the database using the Entity Framework.

A note on Relationships and Lazy Loading

To understand the Entity Framework we need to understand some things like naming conventions, relationships  between tables, and relationships between entities. Also, the concept of lazy loading once fully understood will give the power to the developer to use the Entity Framework efficiently.

Note: Since this is an introductory article on Entity Framework we have not discussed these things. Perhaps we will discuss them in a separate article.

Points of interest

Entity Framework has been in use for some time now. But there are many developers who are still getting started with Entity Framework. This article was meant  as an overview of the Entity Framework. This should not be treated as a complete tutorial. Also, the code written is very simple and there is a lot of scope for  optimization but since the idea here is to understand Entity Framework, I tried to keep the code simple and readable rather and optimal.

Note: To run the solution, please change the database path of ConnectionString in the web.config file.

原文:http://www.codeproject.com/Articles/363040/An-Introduction-to-Entity-Framework-for-Absolute-B

ASP.NET MVC- Model- An Introduction to Entity Framework for Absolute Beginners的更多相关文章

  1. [转帖]2016年时的新闻:ASP.NET Core 1.0、ASP.NET MVC Core 1.0和Entity Framework Core 1.0

    ASP.NET Core 1.0.ASP.NET MVC Core 1.0和Entity Framework Core 1.0 http://www.cnblogs.com/webapi/p/5673 ...

  2. ASP.NET Core 1.0、ASP.NET MVC Core 1.0和Entity Framework Core 1.0

    ASP.NET 5.0 将改名为 ASP.NET Core 1.0 ASP.NET MVC 6  将改名为 ASP.NET MVC Core 1.0 Entity Framework 7.0    将 ...

  3. ASP.NET MVC Model验证(五)

    ASP.NET MVC Model验证(五) 前言 上篇主要讲解ModelValidatorProvider 和ModelValidator两种类型的自定义实现, 然而在MVC框架中还给我们提供了其它 ...

  4. ASP.NET MVC Model验证(四)

    ASP.NET MVC Model验证(四) 前言 本篇主要讲解ModelValidatorProvider 和ModelValidator两种类型的自定义实现,前者是Model验证提供程序,而Mod ...

  5. ASP.NET MVC Model验证(三)

    ASP.NET MVC Model验证(三) 前言 上篇中说到在MVC框架中默认的Model验证是在哪里验证的,还讲到DefaultModelBinder类型的内部执行的示意图,让大家可以看到默认的M ...

  6. ASP.NET MVC Model验证(二)

    ASP.NET MVC Model验证(二) 前言 上篇内容演示了一个简单的Model验证示例,然后在文中提及到Model验证在MVC框架中默认所处的位置在哪?本篇就是来解决这个问题的,并且会描述一下 ...

  7. ASP.NET MVC Model验证(一)

    ASP.NET MVC Model验证(一) 前言 前面对于Model绑定部分作了大概的介绍,从这章开始就进入Model验证部分了,这个实际上是一个系列的Model的绑定往往都是伴随着验证的.也会在后 ...

  8. ASP.NET MVC Model绑定(六)

    ASP.NET MVC Model绑定(六) 前言 前面的篇幅对于IValueProvider的使用做个基础的示例讲解,但是没并没有对 IValueProvider类型的实现做详细的介绍,然而MVC框 ...

  9. ASP.NET MVC Model绑定(五)

    ASP.NET MVC Model绑定(五) 前言 前面的篇幅对于IValueProvider的获取位置和所处的生成过程做了讲解,本篇将会对IValueProvider的使用做个基础的示例讲解,读完本 ...

随机推荐

  1. BZOJ 3901 棋盘游戏 解题报告

    这题有个重要性质: 我们设 Flag[i][j] 表示 (i, j) 是否被奇数个操作所覆盖, 也就是操作次数对 2 取模. 设 x = (n + 1) / 2. 那么对于所有的合法的操作方案, 令 ...

  2. win7(x64)+VS2012+cocos2d-x环境的配置以及试运行

    原地址:http://blog.csdn.net/gf771115/article/details/20740993 转自:http://blog.sina.com.cn/s/blog_62df697 ...

  3. opencv for python 之 突出点检测

    opencv下载地址:http://sourceforge.net/projects/opencvlibrary/files/opencv-win/2.4.3/OpenCV-2.4.3.exe/dow ...

  4. DataTable转换List<T>集合的方法

    using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data; ...

  5. ASP.NET生命周期详解

    最近一直在学习ASP.NET MVC的生命周期,发现ASP.NET MVC是建立在ASP.NET Framework基础之上的,所以原来对于ASP.NET WebForm中的很多处理流程,如管道事件等 ...

  6. 李洪强iOS开发之-环信05_EaseUI 使用指南

    李洪强iOS开发之-环信05_EaseUI 使用指南 EaseUI 使用指南 简介 EaseUI 封装了 IM 功能常用的控件(如聊天会话.会话列表.联系人列表).旨在帮助开发者快速集成环信 SDK. ...

  7. 异常情况下的Activity生命周期分析

    情况1:资源相关的系统配置发生改变 资源相关的系统配置发生改变,举个栗子.当前Activity处于竖屏状态的时候突然转成横屏,系统配置发生了改变,Activity就会销毁并且重建,其onPause, ...

  8. 从 Android 静音看正确的查找 bug 的姿势

    0.写在前面 没抢到小马哥的红包,无心回家了,回公司写篇文章安慰下自己TT..话说年关难过,bug多多,时间久了难免头昏脑热,不辨朝暮,难识乾坤...艾玛,扯远了,话说谁没踩过坑,可视大家都是如何从坑 ...

  9. [OJ] Single Number II

    LintCode 83. Single Number II (Medium) LeetCode 137. Single Number II (Medium) 以下算法的复杂度都是: 时间复杂度: O( ...

  10. C#程序中访问配置文件

    在C#编程中,有时候会用到配置文件,那么该如何在程序中获取或修改配置文件中的相关数据呢?下面采用一个简单的C#控制台程序来说明. 新建一个C#控制台程序,打开“解决方案资源管理器”,如下图: 可以看到 ...