LLBL Gen + Entity Framework 程序设计入门
Entity Framework推出有好几年,除了微软的Visual Studio可以做实体框架开发外,第三方的开发工具如LLBL Gen,
Devart Entity Developer也可以用来做设计开发。
设计数据库表Configuration,它的SQL定义如下
IF OBJECT_ID ('dbo.Configuration') IS NOT NULL
DROP TABLE dbo.Configuration
GO CREATE TABLE dbo.Configuration
(
Recnum INT IDENTITY NOT NULL,
MasterKey NVARCHAR (50) NOT NULL,
Description TEXT NULL,
Remark NVARCHAR (400) NULL,
CONSTRAINT PK_X_Config PRIMARY KEY (MasterKey)
)
GO
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
打开LLBL Gen,创建一个新项目,选择Entity Framework v1
这里还有其它版本的Entity Framework。对应关系如下
Entity Framework v1 => Entity Framework 3.5 SP1
Entity Framework v4 => Entity Framework 4/4.5
再到Category Explorer窗口中,选择添加数据库映射,选择数据库类型,设置连接参数
生成实体模型,继续在Category Explorer窗口中,把表添加到当前项目的实体中,如下图所示
验证实体类型,准备生成代码,但是出现以下几个错误:
The Entity "FileType" contains field "FileType" which has the same name as its containing element,something which isn't supported by the Entity Framework
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }映射的实体名字段中,不能包含与实体名称一样的字段。比如,我有一个FileType的表,映射到FileType实体,它包含一个FileType的主键字段,自动生成映射时,这是不允许的。
清除这个错误之后,按F7生成代码,用Visual Studio 2012打开项目,如下图所示
LLBL Gen代码生成器帮忙我们生成Entity Framework所需要的edmx文件,类型定义和DataContext类型。
来看一下生成的类型定义代码,Configuration表映射的实体类型Configuration实体,它的代码如下
/// <summary>Class which represents the entity 'Configuration'.</summary>
[Serializable]
[DataContract(IsReference=true)]
[EdmEntityType(NamespaceName="Entity35Model", Name="Configuration")]
public partial class Configuration : CommonEntityBase
{
#region Class Member Declarations
private System.String _description;
private System.String _masterKey;
private System.Int32 _recnum;
private System.String _remark;
#endregion #region Extensibility Method Definitions
partial void OnDescriptionChanging(System.String value);
partial void OnDescriptionChanged();
partial void OnMasterKeyChanging(System.String value);
partial void OnMasterKeyChanged();
partial void OnRecnumChanging(System.Int32 value);
partial void OnRecnumChanged();
partial void OnRemarkChanging(System.String value);
partial void OnRemarkChanged();
#endregion /// <summary>Initializes a new instance of the <see cref="Configuration"/> class.</summary>
public Configuration() : base()
{
} /// <summary>Factory method to create a new instance of the entity type 'Configuration'</summary>
/// <param name="masterKeyValue">The initial value for the field 'MasterKey'</param>
/// <param name="recnumValue">The initial value for the field 'Recnum'</param>
public static Configuration CreateConfiguration(System.String masterKeyValue, System.Int32 recnumValue)
{
var toReturn = new Configuration();
toReturn.MasterKey = masterKeyValue;
toReturn.Recnum = recnumValue;
return toReturn;
} #region Class Property Declarations
/// <summary>Gets or sets the Description field. </summary>
[DataMember]
[EdmScalarProperty()]
public System.String Description
{
get { return _description; }
set
{
OnDescriptionChanging(value);
this.ReportPropertyChanging("Description");
_description = SetValidValue(value, true);
this.ReportPropertyChanged("Description");
OnDescriptionChanged();
}
} /// <summary>Gets or sets the MasterKey field. </summary>
[DataMember]
[EdmScalarProperty(EntityKeyProperty=true, IsNullable=false)]
public System.String MasterKey
{
get { return _masterKey; }
set
{
if(_masterKey==value)
{
return;
}
OnMasterKeyChanging(value);
this.ReportPropertyChanging("MasterKey");
_masterKey = SetValidValue(value, false);
this.ReportPropertyChanged("MasterKey");
OnMasterKeyChanged();
}
} /// <summary>Gets or sets the Recnum field. </summary>
[DataMember]
[EdmScalarProperty(IsNullable=false)]
public System.Int32 Recnum
{
get { return _recnum; }
private set
{
OnRecnumChanging(value);
this.ReportPropertyChanging("Recnum");
_recnum = SetValidValue(value);
this.ReportPropertyChanged("Recnum");
OnRecnumChanged();
}
} /// <summary>Gets or sets the Remark field. </summary>
[DataMember]
[EdmScalarProperty()]
public System.String Remark
{
get { return _remark; }
set
{
OnRemarkChanging(value);
this.ReportPropertyChanging("Remark");
_remark = SetValidValue(value, true);
this.ReportPropertyChanged("Remark");
OnRemarkChanged();
}
} #endregion
}
LLBL Gen让生成的实体类型派生于CommonEntityBase,这个类型派生于EntityObject,定义如下
/// <summary>Class which is the common base class for all generated entity classes.</summary>
/// <remarks>As all non-subtype entity classes derive from this class, use a partial class of this class to implement code which is shared among all generated entity classes</remarks>
[DataContract(IsReference = true)]
[Serializable]
public abstract partial class CommonEntityBase : EntityObject
{
#region Class Extensibility Methods
/// <summary>Method called from the constructor</summary>
partial void OnCreated();
#endregion /// <summary>Initializes a new instance of the <see cref="CommonEntityBase"/> class.</summary>
protected CommonEntityBase() : base()
{
OnCreated();
} }
可以在这个类型中,创建一些公共的方法以方便在生成的实体类型中使用。
LLBL Gen为实体框架的实体的每个属性添加了二个跟踪机制方法:Changing和Changed方法。这里可以写我们实体的业务逻辑。比如在采购单中,用户改变单价时,自动重新计算金额(金额=数量*单价)。
以备注属性为例子,请看下面的代码
/// <summary>Gets or sets the Remark field. </summary>
[DataMember]
[EdmScalarProperty()]
public System.String Remark
{
get { return _remark; }
set
{
OnRemarkChanging(value);
this.ReportPropertyChanging("Remark");
_remark = SetValidValue(value, true);
this.ReportPropertyChanged("Remark");
OnRemarkChanged();
}
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
partial void OnRemarkChanging(System.String value);
partial void OnRemarkChanged();
这二个方法都是partial方法,如果我们没有定义方法体,则编译时,它会被忽略。partial方法是C# 3.0才引入的特性,为方便代码生成器与开发人员之间的合作更紧密。试想一下,怎么在不修改代码生成器生成的方法的情况下,添加自定义的业务代码到类型的方法,属性中去呢?答案是partial方法。
同时,因为生成的实体类型已经加了partial关键字,所以我们可以再加入一个同名的实体类型,用来写业务逻辑,而不更改代码生成器自动生成的代码。
最后,写一个测试方法,让它读取系统的配置表Configuration中的数据:
public static void Main(string[] args)
{
Entity35DataContext entity35DataContext = new Entity35DataContext();
var configurations = from item in entity35DataContext.Configurations
select item; foreach (var dbDataRecord in configurations)
{
string companyCode = dbDataRecord.MasterKey; }
}
一行代码即可完成数据库的读取,而且读取的数据是强类型,非常方便。
一般在入门例子中,容易出错的地方是配置文件的内容,来看一下App.config文件的内容:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<!-- please adjust the connection string embedded in the element below to target the proper catalog / server using the proper user / password combination -->
<add name="ConnectionString.SQL Server (SqlClient)" connectionString="metadata=res://*/Entity35.csdl|res://*/Entity35.ssdl|res://*/Entity35.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=Framework;integrated security=SSPI;persist security info=False;packet size=4096"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }这里是设置连接字符串的地方,从生成的ObjectContext类型中,可以看到不带参数的构造方法为从这里读取连接字符串,它的其它的几个方法,如下代码所示
/// <summary>Initializes a new instance of the <see cref="Entity35DataContext"/> class using the connection string found in the 'Entity35' section of the application configuration file.</summary>
public Entity35DataContext() : base("name=ConnectionString.SQL Server (SqlClient)", "Entity35Entities")
{
Initialize();
} /// <summary>Initializes a new instance of the <see cref="Entity35DataContext"/> class</summary>
public Entity35DataContext(string connectionString) : base(connectionString, "Entity35Entities")
{
Initialize();
} /// <summary>Initializes a new instance of the <see cref="Entity35DataContext"/> class</summary>
/// <param name="connection">Ready to use EntityConnection object to be used with this context</param>
public Entity35DataContext(System.Data.EntityClient.EntityConnection connection) : base(connection, "Entity35Entities")
{
Initialize();
}
Entity Framework的连接字符串与经常写的SQL Server的SqlConnection的字符串有所区别,要指定依据edmx生成的三个文件的位置,因为edmx文件的Build Action为EntityDeploy,所以它会被嵌入到生成的程序集中。
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
用.NET Reflector载入生成的实体程序集,查看它的资源文件,如上图所示,三个资源文件被嵌入在程序集中。
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
LLBL Gen + Entity Framework 程序设计入门的更多相关文章
- Entity Framework 程序设计入门二 对数据进行CRUD操作和查询
前一篇文章介绍了应用LLBL Gen生成Entity Framework所需要的类型定义,用一行代码完成数据资料的读取, <LLBL Gen + Entity Framework 程序设计入门& ...
- Entity Framework实体模型 入门视频教程
Entity Framework实体模型 入门视频教程 恢复内容开始--- 第一步 创建一个 控制台应用程序 第二步 创建一个ADO.NET 数据实体模型 DbModel.edmx 需要跟数据库进行连 ...
- Entity Framework快速入门--ModelFirst
Entity Framework带给我们的不仅仅是操作上的方便,而且使用上也很是考虑了用户的友好交互,EF4.0与vs2010的完美融合也是我们选择它的一个理由吧.相比Nhibernate微软这方面做 ...
- Entity Framework快速入门--IQueryable与IEnumberable的区别
IEnumerable接口 公开枚举器,该枚举器支持在指定类型的集合上进行简单迭代.也就是说:实现了此接口的object,就可以直接使用foreach遍历此object: IQueryable 接口 ...
- 使用MVC5的Entity Framework 6入门 ---- 系列教程
使用MVC5的Entity Framework 6入门(十二)——为ASP.NET MVC应用程序使用高级功能 为ASP.NET MVC应用程序使用高级功能这是微软官方教程Getting Starte ...
- 实体框架(Entity Framework)快速入门--实例篇
在上一篇 <实体框架(Entity Framework)快速入门> 中我们简单了解的EF的定义和大体的情况,我们通过一步一步的做一个简单的实际例子来让大家对EF使用有个简单印象,看操作步骤 ...
- Entity Framework 新手入门友好实例
起因 因为实习的原因,程序之中用到了较多的数据库操作逻辑.如果每一处数据库操作都手写的话,工作量较大且后期不易于维护,所以希望能通过 ORM 框架来解决这两个问题. 在昨天之前,对于 ORM 这个词汇 ...
- Entity Framework Core 入门(2)
安装 EF Core 将 EF Core 添加到不同平台和常用 IDE 中的应用程序的所需步骤汇总. 分步入门教程 无需具备 Entity Framework Core 或任何特定 IDE 的原有知识 ...
- entity framework 新手入门篇(3)-entity framework实现orderby,count,groupby,like,in,分页等
前面我们已经学习了entityframework的基本的增删改查,今天,我们将在EF中实现一些更加贴近于实际功能的SQL方法. 承接上面的部分,我们有一个叫做House的数据库,其中包含house表和 ...
随机推荐
- 用js写的比较简单3D旋转效果
HTML代码如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...
- 『TCP/IP详解——卷一:协议』读书笔记——11
2013-08-23 20:00:18 第4章 ARP:地址解析协议 4.1 引言 ARP(Address Resolution Protocol,地址解析协议)是获取物理地址的一个TCP/IP协议. ...
- 如何安装win10+Red Hat Enterprise Linux双系统?
1,如何安装win10+Red Hat Enterprise Linux双系统???? 有很多人(没做过调查,可能就我自己想装吧)想要安装Red Hat Enterprise Linux系统,但是又不 ...
- Jquery 表单验证
<html> <head> <meta http-equiv="content-type" content="tex ...
- 深入浅出C#中的静态与非静态
C#语言静态类 vs 普通类 C#语言静态类与普通类的区别有以下几点: 1)C#语言静态类无法实例化而普通类可以: 2)C#语言静态类只能从System.Object基类继承:普通可以继承其它任何非 ...
- Android中<original-package>标签含义
在AndroidManifest.xml中,<original-package>与<manifest package=...>中的区别:<original-package ...
- 第一次自己写jquery图片延迟加载插件,不通用,但修改一下还是可以使用到很多页面上的
不断修改完善中…… /*! * jquery.lazyoading.js *自定义的页面图片延迟加载插件,比网上的jquery.lazyload简单,也更适合自己的网站 *使用方法: 把img 的cl ...
- JavaScript this用法总结
在JavaScript中,this关键字可以说是最复杂的机制之一.对this的作用机制缺乏比较深入的理解很容易在实际开发中出现问题. 1.this的作用 为什么要在JavaScript中使用this呢 ...
- 【TextBox】重写右键菜单
参考资料 http://bbs.csdn.net/topics/390324356 http://www.cnblogs.com/ycxy/archive/2012/10/09/2716852.htm ...
- centos7 memcached+memagent 集群
1. 安装libevent wget https://github.com/libevent/libevent/releases/download/release-2.0.22-stable/libe ...