您的位置:首页 > 其它

第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>
}


运行浏览器查看结果:

手机
安卓手机

手机
苹果手机

电脑
台式电脑

电脑
笔记本

电脑
一体机
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐