Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 45 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
45
Dung lượng
1,88 MB
Nội dung
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 AddFunction 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 VisualStudio 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 AddEntity. 7. Call the entity Customer. 8. Change the key property name to CustomerID (Figure 8-15). 9. Right-click on Customer and select AddScalar 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 VisualStudio 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 AddAssociation 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. VisualStudio 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. [...]... first development in Visual Studio 201 0VisualStudio 201 0 now has a model designer that you can use to create a database from This allows you to use Visual Studio as a database modeling tool instead of relying on third party modeling tools, which can be very expensive While modeling in VisualStudio 201 0 doesn’t cover every single option you can use when creating a database, combined with a good schema... 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 VS 200 8’s ASP .NET Web Site project but with new changes in ASP .NET Web Application as discussed below) The ASP .NET Web projects... Chapter 2 for details of multitargeting changes that will affect ASP .NET developers ASP .NET developers should be aware that VS 201 0 has two different versions of the development web server: one for NET 2 .0 and the other for NET4.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... http://codebetter.com/blogs/ian_cooper/archive/ 200 8 /06 /26/the-criticism-ofthe-entity-framework-is-not-just-around-domain-driven-design.aspx • http://efvote.wufoo.com/forms/ado -net- entity-framework-vote-of-noconfidence/ • http://ormbattle .NET/ • 206 Programming Entity Framework by Julia Lerman (O’Reilly, 200 9); a fantastic book— can’t recommend enough) http://ayende.com/blog/ CHAPTER 9 WCF Data Services Availability: NET 3.5SP1 (limited... What follows is the default Web.config file that is generated for an ASP .NET 4.0 empty web project (the standard ASP .NET project has a larger Web.config as contains authentication and membership stuff as well) 226 CHAPTER 10 ASP .NET ... Entity Framework to provide this information: 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 208 VisualStudio will ask you about placing these files in the App_Code directory Agree to this CHAPTER 9 5 WCF DATA SERVICES Visual Studio will now ask you how you want it to generate the model... 4 of the Entity Framework will be a game changer I have been working with VisualStudio 201 0 since the first public beta and I am very happy to see where the Entity Framework is going The product team has been listening to users and a majority of the issues with the first version of Entity Framework have been addressed with version 4 I am personally very excited about the features that allow for persistence... 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 files have become To some extent, this bloat was due to ASP .NET 3 .0 and 3.5 using version 2 of the CLR and, in order to introduce... started Open Visual Studio and create a new ASP .NET web site; change the Web location dropdown to HTTP and enter the location as http://localhost/Chapter9/ 207 CHAPTER 9 WCF DATA SERVICES WARNING Hosting WCF Data Services in IIS on one machine gave me HTTP 500 whenever I tried to query data I never got to the bottom of why this was, so all I can say is if you experience this try working with the local... Generation Templates VS 201 0 contains a number of T4 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 . [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 . first development in Visual Studio 201 0. Visual Studio 201 0 now has a model designer that you can use to create a database from. This allows you to use Visual Studio as a database modeling tool. [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'