2013年5月31日 星期五

Entity Framework–Model First, Part 1 (Desing Model)

No classes yet, no database yet, would like to work with a visual designer

1. Design model

2. Generate database schema

3. Execute script to create database

image

 

ADO.NET Entity Data Model  => SalesOrder.edmx

image

Select Empty model

image

After click Finish button, 2 references (EntityFramework & System.Data.Entity) add into project. And SalesOrder.edmx has been created with several files.

image

Now we can start to add the first Entity, there are 2 approaches

1. By click on Toolbox, Entity

2. Right-click mouse on any place –> Add New –> Entity…

image

1. A window will pop-up, then we can start typing Entity name but system auto fill Entity Set

2. The Create key property will create an identical key field with default Property name = Id, but we can overwrite it manually (for example, CustomerId)

image

After that, a property added into the model with a special key icon

image

To add another new property, we have 2 choices

1. Right-click on model –> Add New –> Scalar Property

2. Press Insert button on keyboard

image

Add a Name property, see its Property window. We will let it as default value here.

image

Add another Entity, Order. But this time we change its Property name (key field) to OrderId

image

Add a new Scalar property (OrderDate), but change its Type to DataTime

image

Add a new Scalar property (ShipToAddress), but change its Type to Geography

image

Now we are going to add an Association between Customer and Order entities, right-click –> Add New –> Association…

image

By default, an Add Association windown will pop-up

1. Make sure the relationship in between is 1:1, 1:many, or many:many

2. Add foreign key properties to the ‘xxx’ Entity, so that a foreign key property will be added into (see next picture, 2)

image

Three new properties added

1. Order (Navigation property) added into Customer

2. CustomerId (ForeignKey property) added into Order

3. Customer (Navigation property) added into Order

We can also see a new line in between to say there is 1 to many relationship

image

Click on that line to see its Association property windown

image

The Cascade of End1 OnDelete means application will delete its cascade entity together when delete itself. For example, delete Customer will also delete its Orders together.

image

Add a new property, Industry. But change 3 properties

1. Max Length = 50

2. Unicode = True

3. Default Value = Bank

Later (this and next blog) we will see the difference

image

Click Save All button, sometimes it will show a confirm message because you already opened some files. Click Yes to All to reload them.

image

SalesOrder.Context.cs

image

Change on overall EntityModel property by right-click on any blank space, change Entity Container Name to be more meaningful, for example, SalesOrderDBContext

image

Customer.cs

image

Order.cs

image

沒有留言:

張貼留言