Apress dot NET Test Automation Recipes_4 potx

45 362 0
Apress dot NET Test Automation Recipes_4 potx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

CHAPTER 8  ENTITY FRAMEWORK 192 Patient.Demographic.FirstName Patient.Demographic.Age Patient.Demographic.LastName Patient.Clinical.BloodType Patient.Financial.InsurerName Previously, if you wanted to accomplish this it was necessary to manually edit the CSDL, but as of EF4 you can accomplish this in the designer. Let’s see how to work with this feature with our Film entity. 1. Select the Film entity. 2. Hold down the Ctrl key and select the Description and Length properties (Figure 8-11). 3. Right-click and select the Refactor into New Complex Type option on the context menu. Figure 8-11. Refactoring description and Length into a complex type 4. VS will create a new property called ComplexProperty: rename this property to Detail. 5. If you open Program.cs you will now be able to access these properties using code similar to the following: Film Film = new Film(); Film.Detail.Description = "New film"; Film.Detail.Length = 200; CHAPTER 8  ENTITY FRAMEWORK 193  TIP To undo this change, remove the Film table from the model designer and then add it in again by right- clicking and selecting Update Model from Database. Complex Types from Stored Procedures The function import wizard will now create complex types from stored procedures. For example, let's imagine we wanted to add a method to our Film entity to return information about some of the crew, which is retrieved using the following stored procedure (mocked up for ease of use): CREATE PROCEDURE FilmGetCrewInfo @filmID int AS SELECT 'James Cameron' as Director, 'Arnold Schwarzenegger' as LeadActor1, 'Linda Hamilton' as LeadActor2 1. Go to the Model Browser window (tab next to Solution Explorer). 2. Right-click on the Complex Types folder and add a new complex type called FilmCrew. 3. Right-click on the newly created complex type and add three new string scalar properties called Director, LeadActor1, and LeadActor2 (Figure 8-12). Figure 8-12. Creating a new complex type 4. Open Chapter8.Model.edmx and on the designer surface right-click and select the Update Model from Database option. CHAPTER 8  ENTITY FRAMEWORK 194 5. Under the Stored Procedures node select the FilmGetCrewInfo stored procedure and click Finish. 6. Right-click on the designer surface and select AddFunction Import to bring up the screen shown in Figure 8-13. (I also clicked Get Column Information button when completed the other information to populate the stored procedure column information section). Figure 8-13. Add function import screen 7. Enter the function import name GetCrewInfo. 8. Select the stored procedure name FilmGetCrewInfo. 9. Select Complex in the Returns a Collection Of radio button options and then FilmCrew on the dropdown (notice how you have the option to create a complex type from the results of the stored procedure). 10. Click OK. The EF designer will now have added this function to the context where it can be accessed as follows (note you could then move this into your entity using partial classes): var crew = ctx.GetCrewInfo(1); Model Defined Functions Model defined functions allow you to define reusable functions at a model level. To create them at present you must modify the .edmx file directly, although this will probably change in future versions of CHAPTER 8  ENTITY FRAMEWORK 195 EF. In our convoluted example we will create a new property for our Film entity that will return the Film title and description separated by a space. 1. Right-click on the Chapter8Model.edmx file and select Open With. 2. Select XML Editor. 3. Find the following section: <edmx:ConceptualModels> <Schema Namespace="BookModel" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2008/09/edm"> 4. Add the following inside the previous section: <Function Name="LongFilmDescription" ReturnType="Edm.String"> <Parameter Name="Film" Type="BookModel.Film"> </Parameter> <DefiningExpression> Trim(Film.Title) + " " + Film.Description </DefiningExpression> </Function> 5. Open Program.cs and add the following using directive: using System.Data.Objects.DataClasses; 6. Unfortunately LINQ to Entities doesn’t yet know about the LongFilmDescription function, so we have to tell it by creating a static class decorated with the [EdmFunction] attribute to allow us to access it. Add the following code in Program.cs. public static class MDF { [EdmFunction("BookModel", "LongFilmDescription")] public static string LongFilmDescription(Film f) { throw new NotSupportedException("This function can only be used in a query"); } } 7. Once this is done we can now utilize our function in L2E queries as follows: var query = from f in ctx.Films select new { FullName = MDF.LongFilmDescription(f) }; Model First Generation EF4 allows you to create your entity model in Visual Studio and use it to generate and update database structure. At the time of writing this works only with SQL Server. This facility is great for users unfamiliar with SQL or in situations where you do not have access to the database. 1. Create a new C# console project called Chapter8.ModelFirst. 2. Add a new ADO.NET Entity Data Model called CustomerModel. 3. Click Next. CHAPTER 8  ENTITY FRAMEWORK 196 4. Select Empty model (Figure 8-14) on the next step and click Finish. Figure 8-14. Select empty model option 5. Open the newly created empty CustomerModel.edmx. 6. Right-click on the design surface and select AddEntity. 7. Call the entity Customer. 8. Change the key property name to CustomerID (Figure 8-15). 9. Right-click on Customer and select AddScalar Property. Call it Firstname. 10. Add three more properties: Lastname, Company, Phone. 11. Add another entity called Address. 12. Change the key property name to AddressID . 13. Add five scalar properties to Address called Address1, Address2, Address3, City, and PostalCode (Figure 8-16). CHAPTER 8  ENTITY FRAMEWORK 197 Figure 8-15. Adding an entity to our blank model Figure 8-16. Our manually created Customer and Address entities CHAPTER 8  ENTITY FRAMEWORK 198 14. We need to give Visual Studio a bit more information about the fields for this entity; otherwise, when it creates the database structure all fields will be created in the format varchar(max). Select the Firstname field; then in the Properties window set the MaxLength property to 100. 15. Repeat this for the other fields (Figure 8-17). Figure 8-17. Setting field length properties 16. We now need to link our Customer and Address entities. Right-click on the design surface and select the AddAssociation option. You'll see the screen in Figure 8-18. Figure 8-18. Adding an association CHAPTER 8  ENTITY FRAMEWORK 199 17. Accept the association defaults and then click OK. 18. Select the Model Browser tab next to the Solution Explorer tab. 19. Right-click on CustomerModel node and select Generate Database from Model (Figure 8-19). Figure 8-19. Generating database schema from Entity model 20. The Choose Your Data Connection dialog will now pop up. 21. Select the connection we used earlier and select “Yes, include the sensitive data in the connection string” option and click Next. Visual Studio will then generate the necessary SQL to create a structure to hold these entities (Figure 8-20). CHAPTER 8  ENTITY FRAMEWORK 200 Figure 8-20. Generated T-SQL for our EDM The following is an excerpt of some of the T-SQL that will be generated: Creating table 'Customers' CREATE TABLE [dbo].[Customers] ( [CustomerID] int NOT NULL, [Firstname] nvarchar(100) NOT NULL, [Lastname] nvarchar(100) NOT NULL, [Company] nvarchar(100) NOT NULL, [Phone] nvarchar(100) NOT NULL ); GO Creating table 'Addresses' CREATE TABLE [dbo].[Addresses] ( [AddressID] int NOT NULL, [Address1] nvarchar(100) NOT NULL, [Address2] nvarchar(100) NOT NULL, [Address3] nvarchar(100) NOT NULL, [City] nvarchar(100) NOT NULL, [PostalCode] nvarchar(100) NOT NULL ); GO CHAPTER 8  ENTITY FRAMEWORK 201 Creating all Primary Key Constraints Creating primary key on [CustomerID] in table 'Customers' ALTER TABLE [dbo].[Customers] WITH NOCHECK ADD CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED ([CustomerID] ASC) ON [PRIMARY] GO Creating primary key on [AddressID] in table 'Addresses' ALTER TABLE [dbo].[Addresses] WITH NOCHECK ADD CONSTRAINT [PK_Addresses] PRIMARY KEY CLUSTERED ([AddressID] ASC) ON [PRIMARY] GO Creating all Foreign Key Constraints Creating foreign key on [CustomerCustomerID] in table 'Addresses' ALTER TABLE [dbo].[Addresses] WITH NOCHECK ADD CONSTRAINT [FK_CustomerAddress] FOREIGN KEY ([CustomerCustomerID]) REFERENCES [dbo].[Customers] ([CustomerID]) ON DELETE NO ACTION ON UPDATE NO ACTION GO 22. Click Finish. 23. You will receive a warning (Figure 8-21)—click Yes. Figure 8-21. Warning displayed on generated T-SQL That’s it—you can now run this SQL on your database and use the EDM in the standard way. Foreign Keys In previous versions of EF, foreign key fields on entities were hidden from the developer in the generated model. Developers were expected to access the related entity directly instead of querying foreign key fields. This could mean making some additional database queries to join entities and writing some tedious code. [...]... number of new types of ASP .net project and some modifications to existing types: • New Empty ASP .NET Web Application (just the bare minimum) • New Silverlight 1.0 Web Site (erm, time to move on) • New ASP .NET AJAX Server Control and Server Control Extender • New ASP .NET MVC 2 Web Application • Modified ASP .NET Web Site and a modified ASP .NET Web Application (like VS2008’s ASP .NET Web Site project but... retrieve results formatted as JSON using the HttpWebRequest class in C#: System .Net. HttpWebRequest Request = (System .Net. HttpWebRequest)System .Net. HttpWebRequest.Create( "http://localhost/Chapter9/MovieService.svc/Films(1)" ); Request.Method = "GET"; Request.Accept = "application/json"; System .Net. HttpWebResponse Response = (System .Net. HttpWebResponse)Request.GetResponse(); using (System.IO.StreamReader sr... Chapter 2 for details of multitargeting changes that will affect ASP .NET developers ASP .NET developers should be aware that VS2010 has two different versions of the development web server: one for NET 2.0 and the other for NET 4.0 applications IDE Changes Several enhancements have been made to the IDE and designer that will interest ASP .NET developers • CSS 2.1 compliance has been improved • Designer is... Services? Scott Guthrie spoke to RedDevNews.com regarding this (before the name changes): "Is NET RIA Services going to be preferred over ADO .NET DataServices for Silverlight Data Access? No The bits that are being released today for RIA Services actually build on top of ADO .NET DataServices So you can think of ADO .NET DataServices as providing a kind of lower layer RAW/REST API, and then RIA Services as... returned XML in a browser such as Internet Explorer while we are testing it However, by default when Internet Explorer processes the results of a data service, it will think that it is working with an RSS feed as the data is returned in AtomPub form This is not very helpful for us, so to see the raw XML we need to change a setting in IE: 1 Open IE and go to the Tools Internet Options Content tab 2 Click the... ASP .NET Web Site project but with new changes in ASP .NET Web Application as discussed below) The ASP .NET Web projects now contain common authentication and profile functionality, a master page with a simple layout and jQuery scripts (see Figure 10-1) 225 CHAPTER 10 ASP .NET Figure 10-1 New Web Application Project template Web.config One of the aspects of ASP .NET that irritated me was how bloated Web.config... http://efvote.wufoo.com/forms/ado -net- entity-framework-vote-of-noconfidence/ • http://ormbattle .NET/ • 206 Programming Entity Framework by Julia Lerman (O’Reilly, 2009); a fantastic book— can’t recommend enough) http://ayende.com/blog/ CHAPTER 9 WCF Data Services Availability: NET 3.5SP1 (limited functionality) onwards WCF Data Services (previously “Astoria” and ADO .NET Data Services) allows data to... The latest release of WCF Data Services contains much-needed paging and projection features and seems to be a very useful technology Interested developers should also take a look at WCF RIA Services, which builds on top of WDS, adding many additional features Further Reading • http://blogs.msdn.com/astoriateam/ • http://msdn.microsoft.com/en-us/library/cc907912.aspx 223 CHAPTER 10 ASP .NET ASP .NET is... well (http://gregdoesit.com/2009/08/ nhibernate-vs-entity-framework-a-performance -test/ ) and I heartily recommend you investigate it further References/Further reading • • http://thedatafarm.com/blog/ • http://en.wikipedia.org/wiki/ADO .NET_ Entity_Framework • http://blogs.msdn.com/efdesign/ • http://blogs.msdn.com/adonet/ • http://codebetter.com/blogs/ian_cooper/archive/2008/06/26/the-criticism-ofthe-entity-framework-is-not-just-around-domain-driven-design.aspx... templates At the time of writing there are two templates available: ADO .NET EntityObject Generator and ADO .NET Self-Tracking Entity Generator To use the templates, simply right-click on the designer surface and select Add Code Generation Item 203 CHAPTER 8 1 ENTITY FRAMEWORK Select the template you want to use (Figure 8-22) Figure 8-22 ADO .NET templates 2 The template will then be added to your project (default . ADO .NET Entity Data Model called CustomerModel. 3. Click Next. CHAPTER 8  ENTITY FRAMEWORK 196 4. Select Empty model (Figure 8- 14) on the next step and click Finish. Figure 8- 14. Select. 1. Add a new ADO .NET entity data model to the project. 2. Call the ADO .NET entity data model Chapter9Model.edmx. 3. Click Add. Figure 9-1. Adding ADO .NET entity data model 4. Visual Studio. from normal ADO .NET development will likely not miss the features that aren’t included, since you can’t do things like lazy loading with ADO .NET datasets or inline SQL. Version 4 of the Entity

Ngày đăng: 19/06/2014, 22:20

Mục lục

  • Prelim

  • Contents at a Glance

  • Contents

  • About the Author

  • About the Technical Reviewer

  • Acknowledgments

    • Contributors

    • Introduction

      • …But We Will Give You All This!

      • Code Examples

      • Danger—Work in Progress!

      • Introduction

        • Versions

        • What Is .NET 4.0 and VS2010 All About?

          • Efficiency

          • Maturation of Existing Technologies

          • Extensibility

          • Influence of Current Trends

          • Multicore Shift

          • Unit Testing and Test-Driven Development

          • Cloud Computing

          • What Do Others Think About .NET 4.0?

            • Mike Ormond (Microsoft Evangelist)

            • Eric Nelson (Microsoft Evangelist)

            • Craig Murphy (MVP and developer community organizer)

Tài liệu cùng người dùng

Tài liệu liên quan