2013年5月14日 星期二

Entity Framework–Code First

Address.cs

image

 

AddressType.cs

image

 

Customer.cs

image

 

Order.cs

image

 

New project, SalesModel.DataLayer

image

 

SalesModelContext.cs : DbContext

image

 

Install Entity Framework Power Tools, click TOOLS –> Extensions and Updates…

image

Search and Download it

image

 

Run “View Entity Data Model(Read-only)” by right click on the .cs file

image

 

Error 1, incorrect connection string, but the error is misleading, since we don’t need any connection string is this moment.

image

Solution: Set this project as StartUp project to refer to connection info inside App.config.

 

Error 2, no key defined for ContactDetail.

image

 

Entity Framework has 2 ways to auto define the key field of this class. Look for property name, if name is

1. Id

2. [type] + Id  => in this example, it should be ContactDetailId, not CustomerId

image

 

Solution, using DataAnnotation, [Key]

image

 

Error 3, no relationship definition

image

 

Solution, add [ForeignKey(name of associated foreign key)]

image

 

After all, the read-only entity data model will generate and show.

image

沒有留言:

張貼留言