17.C#:Entity Framework快速入门--实例篇

之前的那篇MSDN上翻译过来的EF写得并不好,没有操作性,这里结合网上一片有实例的博客,结合自己的操作过程,作以下说明:

1.使用VS2010和C#语言,所以要有Oracle数据库服务器,并且要安装VS和Oracle之间的连接组件,我这里安装为:Oracle Data Access Components for Oracle Client
2.连接数据库后,在PL/SQL Devoloper里面写好SQL建表语句,创建序列和触发器语句(用于主键,否则不能有主键,不然异常提示不符合唯一性约束),运行,提交
3.按照下面博客创建Entity Framework实例,将表格等映射为VS中的类等实体
4.在VS主函数里面写好下面博客里面的代码,运行即可到PL/SQL Devoloper查看修改结果
5.PL/SQL Devoloper里面的代码:
建表:
create table T_Class(
       ID number(8) primary key not null,
       Name varchar(20)
);

create table T_Student(
       ID number(8) primary key not null,
       Name varchar(20),
       ClassID number(8),
       Phone varchar(20),
       Email varchar(30),
       constraint T_Student2T_Class foreign key(ClassID) 
         references T_Class(ID) on delete cascade
);

create table T_Teacher(
       ID number(8) primary key not null,
       Name varchar(20),
       Address varchar(30),
       Phone varchar(20),
       Email varchar(30),
       ClassID number(8),
       constraint T_Teacher2T_Class foreign key(ClassID) 
          references T_Class(ID) on delete cascade
);  

/*
drop table T_Student;
drop table T_Class;
drop table T_Teacher;
*/

/*
insert into T_Class values(2,'Class1'); 
*/
select * from T_Teacher;

select * from T_Class;
delete from T_Teacher;

--序列
create sequence SEQ_T_TEACHER
minvalue 1
maxvalue 9999999999999999999999999999
start with 2
increment by 1
cache 20;

--触发器
create or replace trigger tib_T_Teacher before insert
on T_Teacher for each row
declare
    integrity_error  exception;
    errno            integer;
    errmsg           char(200);
    dummy            integer;
    found            boolean;
begin
    if :new.ID is null or :new.ID = 0 then
       select SEQ_T_Teacher.NEXTVAL INTO :new.ID from dual;
    end if;
exception
    when integrity_error then
       raise_application_error(errno, errmsg);
end;


6.VS2010代码(跟下面一致,多了几句解释)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace myEF
{
    class Program
    {
        static void Main(string[] args)
        {
            //schoolEntities.T_CLASS表示T_Class表,而c表示一条记录结构
            using (var schoolEntities = new SchoolDBEntities())
            {
                var cls = (from c in schoolEntities.T_CLASS
                           where c.ID == 2
                           select c).SingleOrDefault();

                //如果要表示所有记录,必须使用list集合
                //List tList = new List();

                //T_Teacher表示表结构,teacher.T_CLASS表示teacher的外键所在表的表结构
                T_TEACHER teacher = new T_TEACHER();
                //teacher.ID = new Random().Next();
                teacher.ADDRESS = "北京海淀上地";
                teacher.EMAIL = "[email protected]";
                teacher.T_CLASS = cls;
                teacher.NAME = "Flydragon";
                teacher.PHONE = "110";
                schoolEntities.T_TEACHER.AddObject(teacher);

                Console.WriteLine("in");

                try
                {
                    schoolEntities.SaveChanges();
                }
                catch (Exception ex)
                { 
                
                }
            }
            Console.WriteLine("OK");
            Console.ReadKey();
        }
    }
}


Entity Framework快速入门--实例篇 DatabaseFirst

本文来自:http://www.cnblogs.com/fly_dragon/archive/2011/02/20/1958884.html

在上一篇中我们简单了解的EF的定义和大体的情况,我们通过一步一步的做一个简单的实际例子来让大家对EF使用有个简单印象。好,废话少说,直入主题。

第一步:创建控制台项目

这个就不多说了,如果新建项目你还不知道,那先去学学基础吧。

第二步:创建实体模型

在项目上右击 添加新建项目→Ado.Net实体数据模型

如下图所示:

17.C#:Entity Framework快速入门--实例篇_第1张图片

第三步:与现有的数据库进行连接生成EF实体

在做这步之前,首先确定你是否已经有现有数据库,当然在这提供我自己的数据库脚本。

复制代码
 
      
-- --------------------------------------------------
-- Entity Designer DDL Script for SQL Server 2005 , 2008 , and Azure
-- --------------------------------------------------
-- Date Created: 02 / 20 / 2011 09 : 47 : 54
-- Generated from EDMX file: E:\Job\projects\WebTest\EF\Model1.edmx
-- --------------------------------------------------

SET QUOTED_IDENTIFIER OFF;
GO
USE [SchoolDB];
GO
IF SCHEMA_ID(N
' dbo ' ) IS NULL EXECUTE(N ' CREATE SCHEMA [dbo] ' );
GO

-- --------------------------------------------------
-- Dropping existing FOREIGN KEY constraints
-- --------------------------------------------------

IF OBJECT_ID(N
' [dbo].[FK_ClassStudent] ' , ' F ' ) IS NOT NULL
ALTER TABLE [dbo].[T_Student] DROP CONSTRAINT [FK_ClassStudent];
GO
IF OBJECT_ID(N
' [dbo].[FK_ClassTeacher] ' , ' F ' ) IS NOT NULL
ALTER TABLE [dbo].[T_Teacher] DROP CONSTRAINT [FK_ClassTeacher];
GO

-- --------------------------------------------------
-- Dropping existing tables
-- --------------------------------------------------

IF OBJECT_ID(N
' [dbo].[T_Class] ' , ' U ' ) IS NOT NULL
DROP TABLE [dbo].[T_Class];
GO
IF OBJECT_ID(N
' [dbo].[T_Student] ' , ' U ' ) IS NOT NULL
DROP TABLE [dbo].[T_Student];
GO
IF OBJECT_ID(N
' [dbo].[T_Teacher] ' , ' U ' ) IS NOT NULL
DROP TABLE [dbo].[T_Teacher];
GO

-- --------------------------------------------------
-- Creating all tables
-- --------------------------------------------------

-- Creating table ' T_Class '
CREATE TABLE [dbo].[T_Class] (
[ID]
int IDENTITY( 1 , 1 ) NOT NULL,
[Name] nvarchar(max) NOT NULL
);
GO

-- Creating table ' T_Student '
CREATE TABLE [dbo].[T_Student] (
[ID] uniqueidentifier NOT NULL,
[Name] nvarchar(max) NOT NULL,
[ClassID]
int NOT NULL,
[Phone] nvarchar(max) NOT NULL,
[Email] nvarchar(max) NOT NULL
);
GO

-- Creating table ' T_Teacher '
CREATE TABLE [dbo].[T_Teacher] (
[ID]
int IDENTITY( 1 , 1 ) NOT NULL,
[Name] nvarchar(max) NOT NULL,
[Address] nvarchar(max) NOT NULL,
[Phone] nvarchar(max) NOT NULL,
[Email] nvarchar(max) NOT NULL,
[ClassID]
int NOT NULL
);
GO

-- --------------------------------------------------
-- Creating all PRIMARY KEY constraints
-- --------------------------------------------------

-- Creating primary key on [ID] in table ' T_Class '
ALTER TABLE [dbo].[T_Class]
ADD CONSTRAINT [PK_T_Class]
PRIMARY KEY CLUSTERED ([ID] ASC);
GO

-- Creating primary key on [ID] in table ' T_Student '
ALTER TABLE [dbo].[T_Student]
ADD CONSTRAINT [PK_T_Student]
PRIMARY KEY CLUSTERED ([ID] ASC);
GO

-- Creating primary key on [ID] in table ' T_Teacher '
ALTER TABLE [dbo].[T_Teacher]
ADD CONSTRAINT [PK_T_Teacher]
PRIMARY KEY CLUSTERED ([ID] ASC);
GO

-- --------------------------------------------------
-- Creating all FOREIGN KEY constraints
-- --------------------------------------------------

-- Creating foreign key on [ClassID] in table ' T_Student '
ALTER TABLE [dbo].[T_Student]
ADD CONSTRAINT [FK_ClassStudent]
FOREIGN KEY ([ClassID])
REFERENCES [dbo].[T_Class]
([ID])
ON DELETE NO ACTION ON UPDATE NO ACTION;

-- Creating non - clustered index for FOREIGN KEY ' FK_ClassStudent '
CREATE INDEX [IX_FK_ClassStudent]
ON [dbo].[T_Student]
([ClassID]);
GO

-- Creating foreign key on [ClassID] in table ' T_Teacher '
ALTER TABLE [dbo].[T_Teacher]
ADD CONSTRAINT [FK_ClassTeacher]
FOREIGN KEY ([ClassID])
REFERENCES [dbo].[T_Class]
([ID])
ON DELETE NO ACTION ON UPDATE NO ACTION;

-- Creating non - clustered index for FOREIGN KEY ' FK_ClassTeacher '
CREATE INDEX [IX_FK_ClassTeacher]
ON [dbo].[T_Teacher]
([ClassID]);
GO

-- --------------------------------------------------
-- Script has ended
-- --------------------------------------------------
复制代码

然后按照如下所示,选择从数据库生成实体数据模型【当然如果你想使用CodeFirst方式也是可以的,这是后话了】:

17.C#:Entity Framework快速入门--实例篇_第2张图片

新建连接到现有的数据库,如下图所示:

17.C#:Entity Framework快速入门--实例篇_第3张图片

点击下一步,选择我们要生成实体对应的表、试图、存储过程等,如下图所示:

17.C#:Entity Framework快速入门--实例篇_第4张图片

最后点击完成,则系统帮我们生成了数据库实体类以及EDMX的定义文件。

如图所示:

17.C#:Entity Framework快速入门--实例篇_第5张图片

到现在我们前期的准备工作就结束了,我们接下来看看我们怎么使用EF帮我们生成的数据库网关

第四步:写增删改查来讲解EF的基本使用

添加如下代码:

复制代码
 
     
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EF
{
class Program
{
static void Main( string [] args)
{
// 创建数据库访问网关
using (SchoolDBEntities schoolEntities = new SchoolDBEntities())
{
// 查询到老师对应的班级的外键,注意是使用的linq to ef ,它是生成的命令树,然后是生成的sql

var cls
= (from c in schoolEntities.T_Class
where c.ID == 2
select c).SingleOrDefault
< T_Class > ();
// 创建teacher一个实体
T_Teacher teacher = new T_Teacher();
teacher.Address
= " 北京海淀上地 " ;
teacher.Email
= " [email protected] " ;
teacher.T_Class
= cls;

teacher.Name
= " Flydragon " ;
teacher.Phone
= " 110 " ;
// 将创建的实体,放入网关的数据实体的集合
schoolEntities.T_Teacher.AddObject(teacher);
// 写回数据库
schoolEntities.SaveChanges();
}
Console.WriteLine(
" OK " );
}
}
}
复制代码

最终数据库中添加了一条数据,如下图所示:

然后我正好打开了Sql Server Profiler工具我们看一下,EF生成的SQL语句是什么,如下图所示:

17.C#:Entity Framework快速入门--实例篇_第6张图片

最后一个就是执行insert插入数据库表的sql,如下图所示:

17.C#:Entity Framework快速入门--实例篇_第7张图片

好这样我们一个入门的实例程序,就结束了,我们看到最后EF还是生成的SQL执行的。所以EF本身性能的损失也就是根据对实体集合的修改,然后根据edmx的定义最终成sql这段,也就是浪费了点cpu而已,而且ef还会自动帮我们对sql进行优化,所以还是蛮不错的!

你可能感兴趣的:(C#)