使用Entity Framework编程6Word文档下载推荐.docx
- 文档编号:4249648
- 上传时间:2023-05-03
- 格式:DOCX
- 页数:44
- 大小:314.90KB
使用Entity Framework编程6Word文档下载推荐.docx
《使用Entity Framework编程6Word文档下载推荐.docx》由会员分享,可在线阅读,更多相关《使用Entity Framework编程6Word文档下载推荐.docx(44页珍藏版)》请在冰点文库上搜索。
我们覆盖的主题将包括指向其他数据库引擎,部署应用程序,执行数据库有关的任何等。
你也可以学习到数据库初始化器可以用于控制数据库生成过程,添加种子数据到数据库中等。
这在进行自动测试的场景时特别有用。
ControllingtheDatabaseLocation
控制数据库位置
SofaryouhavereliedontheCodeFirstconventiontoselectwhichdatabasetheapplicationtargets.Bydefault,CodeFirsthascreatedthedatabaseonlocalhost\SQLEXPRESSusingthefullyqualifiednameofyourcontextclassforthedatabasename(i.e.,thenamespaceplustheclassname).Therewillbetimeswhenthiswon’tbeappropriateandyouneedtooverridetheconventionandtellCodeFirstwhichdatabasetoconnectto.YoucanmodifyorreplacetheconventionusedtoselectadatabaseusingCodeFirstconnectionfactories.Alternatively,youcanjusttellCodeFirstexactlywhichdatabasetouseforaparticularcontext,usingtheDbContextconstructorsoryourapplicationconfigurationfile.
到目前为止我们都是引用了CodeFirst的默认规则来选择应用程序的数据库目标。
默认情况,CodeFirst会使用localhost\SQLEXPRESS作为目标数据库引擎,并使用context类的全名作为数据库名(即命名空间+类名)。
如果不符合要求你需要覆写默认规则然后告知CodeFirst想要连接到哪个数据库。
你可以CodeFirst的连接工厂来选择数据库,修改或替换默认规则。
可选择地,你也可以使用DbContext构造器或应用程序配置文件来告知CodeFirst对某个特定的上下文使用指定的数据库。
CodeFirstdatabasecreationandinitializationworkswithSQLAzureinthesamewaythatitworkswithanylocaldatabase.Youcanseethisinactionin“Tutorial:
DevelopingaWindowsAzureDataApplicationUsingCodeFirstandSQLAzure”.VendorshavebegunmodifyingtheirdatabaseproviderstosupportCodeFirstaswell.BesuretocheckforthissupportbeforetryingtouseCodeFirstwithoneofthethird-partyproviders.
小贴士:
CodeFirst可以在SQLAzure上使用与任何本地数据库相同的方法进行创建和初始化工作。
你可在First的支持。
在使用CodeFirst与第三方数据库引擎工作前一定要检查是否支持。
ControllingDatabaseLocationwithaConfigurationFile
使用配置文件控制数据库位置
Theeasiestandmostdefinitivewaytocontrolthedatabasethatyourcontextconnectstoisviaaconfigurationfile.Usingtheconfigurationfileallowsyoutobypassalldatabaselocation–relatedconventionsandspecifytheexactdatabaseyouwanttouse.Thisapproachisparticularlyusefulifyouwanttochangetheconnectionstringofyourcontexttopointtoaproductiondatabaseasyoudeployyourapplication.
Bydefault,theconnectionstringthatyouaddtoyourconfigurationfileshouldhavethesamenameasyourcontext.Thenameoftheconnectionstringcanbeeitherjustthetypenameorthefullyqualifiedtypename.In“ControllingConnectionStringNamewithDbContextConstructor”onpage132,youwillseehowtouseaconnectionstringwithanamethatdoesnotmatchyourcontextname.AddanApp.configfiletoyourBreakAwayConsoleapplicationwithaBreakAwayContextconnectionstring,asshowninExample6-1.
控制数据库连接最简单也最可靠的方法是使用配置文件。
配置文件可以帮你绕过所有与数据库位置相关的约定,并能指定到你想使用的确切数据库。
这种方法是非常有用的,如果你想改变你的上下文的连接字符串指向一个生产数据库,为您部署应用程序。
默认情况下,您添加到您的配置文件的连接字符串应该与context有相同的名称。
连接字符串的名称可以是类型名称或完全限定的类型名称。
在后面“使用DbContext构造器控制连接字符串名称”,你会看到如何让连接字符串的名称不匹配上下文的名称。
添加一个App.config文件到BreakAwayConsole应用程序,内中包含BreakAwayContext的连接字符串,如例6-1所示。
Example6-1.ConnectionstringspecifiedinApp.config
<
?
xmlversion="
1.0"
>
configuration>
<
connectionStrings>
addname="
BreakAwayContext"
providerName="
System.Data.SqlClient"
connectionString="
Server=.\SQLEXPRESS;
Database=BreakAwayConfigFile;
Trusted_Connection=true"
/>
/connectionStrings>
/configuration>
ForthosefamiliarwithcreatingconnectionstringswhenyourapplicationusesanEDMXfile,noticethatthisisnotanEntityConnectionStringbutsimplyadatabaseconnectionstring.WithCodeFirst,youhavenoneedtoreferencemetadatafilesortheSystem.Data.EntityClientnamespace.、
对熟悉使用EDMX文件创建连接字符串的人,请注意这不是一个EntityConnectionString而是一个简单的数据库连接字符串。
使用CodeFirst,你不需要引用元数据文件或System.Data.EntityClient名称空间。
ModifytheMainmethodsothatitcallstheInsertDestinationmethod,asshowninExample6-2.
修改Main方法,调用InsertDestination方法,如代码6-2所示。
Example6-2.MainmethodmodifiedtocallInsertDestination
staticvoidMain()
{
InsertDestination();
}
Runtheapplication,andyouwillnoticethataBreakAwayConfigFiledatabasehasbeencreatedinyourlocalSQLExpressinstance(Figure6-1).
运行应用程序,你会发现,BreakAwayConfigFile数据库实例已在您的本地SQLExpress上创建了(图6-1)。
CodeFirstmatchedtheBreakAwayContextnameofyourcontextwiththeBreakAwayContextconnectionstringintheconfigurationfile.Becauseanentrywasfoundintheconfigurationfile,theconventionforlocatingadatabasewasnotused.TheconnectionstringentrycouldalsohavebeennamedDataAccess.BreakAwayContext,whichisthefullyqualifiednameofthecontext.
CodeFirst使用配置文件中的BreakAwayContext连接字符串匹配名为BreakAwayContext的上下文。
因为在配置文件中发现了一个条目,就不再使用约定来定位数据库。
连接字符串项,也已经被命名为DataAccess.BreakAwayContext,这是上下文的全名。
ControllingDatabaseNamewithDbContextConstructor
使用DbContext的构造器控制数据库名称
You’veseenhowtosettheconnectionstringthatyourcontextwilluseviatheconfigurationfile;
nowlet’slookatsomewaystocontrolthedatabaseconnectionfromcode.SofaryouhavejustusedthedefaultconstructoronDbContext,buttherearealsoanumberofotherconstructorsavailable.Mostoftheseareformoreadvancedscenarios,whichwillbecoveredlaterinthisbook,buttherearetwoconstructorsthatallowyoutoaffectthedatabasebeingconnectedto.
你已经看到如何通过配置文件中的连接字符串设置上下文,现在让我们来看看使用代码来控制数据库连接的方法。
到目前为止,您只使用过DbContext的默认构造函数,还有一些其他可用的构造函数可供使用。
其中大部分是更高级的方法,这将在这本书中进行介绍,有两个构造函数允许你影响连接到的数据库。
Ifyouaddedaconnectionstringtoyourconfigurationfile,asshownintheprevioussection,besuretoremoveitbeforestartingthissection.Rememberthattheconfigurationfileoverrideseverything,includingthefeaturesyouwillseeinthissection.
如果您添加了一个连接字符串到您的配置文件,如在上一节所示,开始本节之前,一定要去掉它。
记住,配置文件压倒一切,包括在本节的功能。
DbContextincludesaconstructorthattakesasinglestringparametertocontrolthedatabasename.Ifyouusethisconstructor,thevalueyousupplywillbeusedinplaceofthefullyqualifiedcontextname.AddaconstructortoBreakAwayContextthatacceptsastringvalueforthedatabasenameandpassesittothebaseconstructor(Example6-3).Noticethatyouarealsoaddingadefaultconstructortoensurethatalltheexistingcodefrompreviouschapterscontinuestowork.
DbContext有一个构造函数使用一个字符串参数来控制数据库的名称。
如果您使用此构造器,您提供的值将被用来代替context的全名。
添加到BreakAwayContext构造函数接受一个数据库名称的字符串值,并把它传递给基构造器(例6-3)。
请注意,您也必须要加入默认的构造器,以确保所有现有的代码从前面的章节继续工作。
Example6-3.Databasenameconstructoraddedtocontext
publicBreakAwayContext()
{}
publicBreakAwayContext(stringdatabaseName)
:
base(databaseName)
ModifytheMainmethodtocallanewSpecifyDatabaseNamemethod(Example6-4).
修改Main方法调用SpecifyDatabaseName方法(Example6-4).
Example6-4.SpecifyDatabaseNamemethodaddedtoapplication
SpecifyDatabaseName();
privatestaticvoidSpecifyDatabaseName()
using(varcontext=
newBreakAwayContext("
BreakAwayStringConstructor"
))
{
context.Destinations.Add(newDestination{Name="
Tasmania"
});
context.SaveChanges();
}
Thisnewmethodusestheconstructoryoujustaddedtospecifyadatabasename.Thisnameisusedinsteadofthefullyqualifiednameofyourcontext.RuntheapplicationandyouwillseethatadatabasenamedBreakAwayStringConstructorhasbeencreatedinyourlocalSQLExpressinstance.
新方法使用的构造器,就是你刚刚添加的,用于指定数据库名称。
使用的此名称,就不是上下文的全名了。
运行应用程序,你会看到一个名为BreakAwayStringConstructor数据库已在您的本地SQLExpress实例中创建。
ControllingConnectionStringNamewithDbContextConstructor
使用DbContext构造器控制连接字符串
Earlierinthischapter,yousawthatyouareabletospecifyadatabasetouseintheconfigurationfilebyaddingaconnectionstringwiththesamenameasyourcontext.IfyouusetheDbContextconstructorthatacceptsadatabasename,Entityramework
willlookforaconnectionstringwhosenamematchesthedatabasename.Inotherwords,withthedefaultconstructor,EntityFrameworkwilllookforaconnectionstringnamedBreakAwayContext,butwiththeconstructorusedinExample6-4,itwillexpectaconnectionstringnamedBreakAwayStringConstructor.
Youcanalsoforcethecontexttogetitsconnectionstringfromtheconfigurationfilebysupplyingname=[connectionstringname]tothisconstructor.Thisway,youdon’tneedtorelyonnamematching,sinceyouareexplicitlyprovidingaconnectionstringname.Ifnoconnectionstringisfoundwiththespecifiedname,anexceptionisthrown.
Example6-5showshowyoucanmodifythedefaultconstructorofbreakAwayContexttoensurethattheconnectionstringisalwaysloadedfromtheconfigurationfile.
在本章的前面,你看到,你可以通过在配置文件中加入与你的上下文的名称相同的连接字符串指定一个数据库。
如果您使用的DbContext构造函数接受一个数据库名,EF框架就会寻找一个与连接字符串的名称相匹配的数据库的名称。
换句话说,默认的构造函数,实体框架会寻找名为BreakAwayContext的连接字符串,而使用与示例6-4中使用的构造函数,它会期望一个名为BreakAwayStringConstructor的连接字符串。
您还可以强制上下文从配置文件中所提供的name=[connectionstringname]获取连接字符串。
这样,你就不需要依靠名称匹配
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 使用Entity Framework编程6 使用 Entity Framework 编程