第003课:EF使用方式二:Model First
2013-08-28 17:21
162 查看
1新建ASP.NETMVC4项目“MvcApplication1”
1.1新建项–>数据–>ADO.NETEntityDataModel
名称:TestDB2.edmx选择Emptymodel
1.2查看生成文件
在web.config中,新增了数据库连接属性DefaultConnection,也新增了:<connectionStrings> <addname="DefaultConnection"connectionString="DataSource=(LocalDb)\v11.0;InitialCatalog=aspnet-MvcApplication1-20130827203245;IntegratedSecurity=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcApplication1-20130827203245.mdf"providerName="System.Data.SqlClient"/> </connectionStrings>
TestDB2.edmx中文件内容
1.3在TestDB2.edmx中设计Entity(Product,ProductCategory)
设计Entity:Product,ProductCategory右键Product查看属性(EntitySetName默认会在Entity名称后面加上Set,最后去除,不然数据表表名会叫ProductSet):
保存后:TestDB2.edmx的变化,如下图
变化的详细内容:
会在TestDB2.tt下新增两个类Product.cs和ProductCategory.cs
Product.cs
//------------------------------------------------------------------------------ //<auto-generated> //此代码是根据模板生成的。 // //手动更改此文件可能会导致应用程序中发生异常行为。 //如果重新生成代码,则将覆盖对此文件的手动更改。 //</auto-generated> //------------------------------------------------------------------------------ namespaceMvcApplication1 { usingSystem; usingSystem.Collections.Generic; publicpartialclassProduct { publicintId{get;set;} publicstringTitle{get;set;} publicvirtualProductCategoryProductCategory{get;set;} } }
ProductCategory.cs
//------------------------------------------------------------------------------ //<auto-generated> //此代码是根据模板生成的。 // //手动更改此文件可能会导致应用程序中发生异常行为。 //如果重新生成代码,则将覆盖对此文件的手动更改。 //</auto-generated> //------------------------------------------------------------------------------ namespaceMvcApplication1 { usingSystem; usingSystem.Collections.Generic; publicpartialclassProductCategory { publicProductCategory() { this.Product=newHashSet<Product>(); } publicintId{get;set;} publicstringTitle{get;set;} publicvirtualICollection<Product>Product{get;set;} } }
保存后:同时会在TestDB2.Context.tt下生成TestDB2.Context.cs
//------------------------------------------------------------------------------ //<auto-generated> //此代码是根据模板生成的。 // //手动更改此文件可能会导致应用程序中发生异常行为。 //如果重新生成代码,则将覆盖对此文件的手动更改。 //</auto-generated> //------------------------------------------------------------------------------ namespaceMvcApplication1 { usingSystem; usingSystem.Data.Entity; usingSystem.Data.Entity.Infrastructure; publicpartialclassTestDB2Container:DbContext { publicTestDB2Container() :base("name=TestDB2Container") { } protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder) { thrownewUnintentionalCodeFirstException(); } publicDbSet<Product>ProductSet{get;set;} publicDbSet<ProductCategory>ProductCategorySet{get;set;} } }
保存后:TestDB2.edmx.diagram中会新增代码,说明实体的信息,包括关系,x,y坐标位置等
<?xmlversion="1.0"encoding="utf-8"?> <edmx:EdmxVersion="3.0"xmlns:edmx="http://schemas.microsoft.com/ado/2009/11/edmx"> <!--EFDesignercontent(DONOTEDITMANUALLYBELOWHERE)--> <edmx:Designerxmlns="http://schemas.microsoft.com/ado/2009/11/edmx"> <!--Diagramcontent(shapeandconnectorpositions)--> <edmx:Diagrams> <DiagramDiagramId="6246fb75e64744499850b69530adcb17"Name="Diagram1"DisplayType="true"> <EntityTypeShapeEntityType="TestDB2.Product"Width="2.375"PointX="0.5"PointY="0.75"/> <EntityTypeShapeEntityType="TestDB2.ProductCategory"Width="2.625"PointX="4"PointY="0.75"/> <AssociationConnectorAssociation="TestDB2.ProductCategoryProduct"/> </Diagram> </edmx:Diagrams> </edmx:Designer> </edmx:Edmx>
2生成数据库
2.1新建数据库TestDB2
2.2在TestDB2.edmx页面空白处,右键选择“从模型生成到数据库…”
新建NewConnection,配置数据库连接到本地SQLServer2008的TestDB2查看生成的SQL语句,点击完成
在TestDB2.edmx同级目录下会生成文件TestDB2.edmx.sql
---------------------------------------------------- --EntityDesignerDDLScriptforSQLServer2005,2008,andAzure ---------------------------------------------------- --DateCreated:08/28/201317:05:48 --GeneratedfromEDMXfile:C:\WorkSpace\Project2013\MvcApplication1\MvcApplication1\TestDB2.edmx ---------------------------------------------------- SETQUOTED_IDENTIFIEROFF; GO USE[TestDB2]; GO IFSCHEMA_ID(N'dbo')ISNULLEXECUTE(N'CREATESCHEMA[dbo]'); GO ---------------------------------------------------- --DroppingexistingFOREIGNKEYconstraints ---------------------------------------------------- ---------------------------------------------------- --Droppingexistingtables ---------------------------------------------------- ---------------------------------------------------- --Creatingalltables ---------------------------------------------------- --Creatingtable'ProductSet' CREATETABLE[dbo].[ProductSet]( [Id]intIDENTITY(1,1)NOTNULL, [Title]nvarchar(max)NOTNULL, [ProductCategory_Id]intNOTNULL ); GO --Creatingtable'ProductCategorySet' CREATETABLE[dbo].[ProductCategorySet]( [Id]intIDENTITY(1,1)NOTNULL, [Title]nvarchar(max)NOTNULL ); GO ---------------------------------------------------- --CreatingallPRIMARYKEYconstraints ---------------------------------------------------- --Creatingprimarykeyon[Id]intable'ProductSet' ALTERTABLE[dbo].[ProductSet] ADDCONSTRAINT[PK_ProductSet] PRIMARYKEYCLUSTERED([Id]ASC); GO --Creatingprimarykeyon[Id]intable'ProductCategorySet' ALTERTABLE[dbo].[ProductCategorySet] ADDCONSTRAINT[PK_ProductCategorySet] PRIMARYKEYCLUSTERED([Id]ASC); GO ---------------------------------------------------- --CreatingallFOREIGNKEYconstraints ---------------------------------------------------- --Creatingforeignkeyon[ProductCategory_Id]intable'ProductSet' ALTERTABLE[dbo].[ProductSet] ADDCONSTRAINT[FK_ProductCategoryProduct] FOREIGNKEY([ProductCategory_Id]) REFERENCES[dbo].[ProductCategorySet] ([Id]) ONDELETENOACTIONONUPDATENOACTION; --Creatingnon-clusteredindexforFOREIGNKEY'FK_ProductCategoryProduct' CREATEINDEX[IX_FK_ProductCategoryProduct] ON[dbo].[ProductSet] ([ProductCategory_Id]); GO ---------------------------------------------------- --Scripthasended ----------------------------------------------------
右键文件“TestDB2.edmx.sql”内容,选择“执行”,会弹出ContectToServer的界面
点击“Contect”,若看到”已成功完成命令”,则说明操作成功!
在Web.config中会新增数据库连接配置属性”TestDB2Container“
<connectionStrings> <addname="TestDB2Container"connectionString="metadata=res://*/TestDB2.csdl|res://*/TestDB2.ssdl|res://*/TestDB2.msl;provider=System.Data.SqlClient;providerconnectionstring="datasource=WIN7-YANG\SQLSERVER2008;initialcatalog=TestDB2;integratedsecurity=True;MultipleActiveResultSets=True;App=EntityFramework""providerName="System.Data.EntityClient"/> </connectionStrings>
2.3查看数据库是否成功生成
3测试一下
ProductSet表中数据ProductCategorySet表中数据
在HomeController.cs中加入如下代码:
publicActionResultIndex() { vartestDB2=newTestDB2Container(); varproducts=testDB2.ProductSet.ToList(); returnView(products); }
在View/Home/Index.cshtml中加入如下代码
@modelIEnumerable<MvcApplication1.Models.Product> @foreach(variteminModel) { <ul> <li>@item.ProductCategory.Title</li> <li>@item.Title</li> </ul> }
运行浏览器查看结果:
手机
安卓手机
手机
苹果手机
电脑
台式电脑
电脑
笔记本
电脑
一体机
相关文章推荐
- 使用EF Model First创建edmx模型,数据库有数据的情况下,如何同时更新模型和数据库
- EF三种编程方式详细图文教程(C#+EF)之Model First
- EF三种编程方式详细图文教程(C#+EF)之Model First
- EF学习和使用(二)ModelFirst
- 使用EF Code-First方式和Fluent API来探讨EF中的关系
- 在ASP.NET中使用SQL Server作为数据库,DB First方式使用EF(EntityFramework)进行开发和部署时的connectionString
- 1.【使用EF Code-First方式和Fluent API来探讨EF中的关系】
- EF三种编程方式详细图文教程(C#+EF)之Model First
- 关于在ASP.NET MVC 中使用EF的Code First的方式来读取数据库时的Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
- 黑马程序员_学习日记76_801ASP.NET(ORM框架CRUD、EF ModelFirst编程方式、延迟加载机制)
- 第004课:EF使用方式三:Code First
- Entity Framework4.0 (二)概述(EF4 的Model First 方法)
- (转 )Entity Framework Code First使用者的福音 --- EF Power Tool使用记之二(问题探究)
- django 命令行方式使用model建数据库
- EF DataBase First生成model的验证
- Entity Framework Code First使用者的福音 --- EF Power Tool使用记之二(问题探究)(转)
- 在使用EFCodeFirst中出现类型“System.Data.Objects.ObjectContext”在未被引用的程序集中定义的解决方案
- MVC 使用EF Code First数据迁移之添加字段
- EF Codefirst方式数据库维护操作
- 使用EF DataBaseFirst做一个简单的MVC3报名网站