Tải bản đầy đủ (.pdf) (7 trang)

Lập trình .net 4.0 và visual studio 2010 part 29 ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (286.03 KB, 7 trang )

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="
xmlns="
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.

×