Preface
The company's latest project decided to use EF. As a beginner in EF, I hope that the old birds will be able to give me some lessons and solutions.
The sample program uses EF 4.1RC + Spring. Net 1.3.1 + ASP. NET MVC3. Open source on CodePlex
Http://efsample.codeplex.com/
Since other open-source frameworks are used, we should declare that the license is Apache 2.0. In fact, as long as the license of each framework is not violated, please use this series of code at will.
Requirement
Let's talk about the project's requirements for ORM.
Basic Requirements
- Add, delete, and modify
- Query
- One-to-multiple
- Many-to-many
- Can be mapped to existing databases (with naming issues)
- Any class can be mapped to the database (the project allows the customer to perform secondary development. In the simplest case, You can map only the class and table structure. This is the main reason why Code First is selected)
- Per-request DbContext lifecycle management.
- Transactions
Scalability
- One-to-one
- Domain inheritance
- Domain dependent Injection
This series will try to cover most of the above issues.
Scenario
Suppose we are going to make a game with the following table structure:
Practice (1)
As the first chapter of the series, our goal is to retrieve data from the database. Like this
Let's start Step 1: Create a domain model
Follow the official blog's aspx "target = _ blank>Walk through, It is easy to write the following code.
Public Class Race: IEntity
{
Public Int Id { Get ; Set ;}
Public String Name { Get ; Set ;}
}
Public Class Hero: IEntity
{
Public Int Id { Get ; Set ;}
Public String Name { Get ; Set ;}
Public Bool IsSuperHero { Get ; Set ;}
Public Virtual Race { Get ; Set ;}
}
Note that the Race attribute in the Hero class is defined as virtual to delay loading. However, unlike NH, if you do not write a virtual file, the system will not report an error. Instead, an empty reference exception will be reported during use.
Here, we can insert a note that it is quite uncomfortable for me to compromise the ORM in the domain model. I have never liked the virtual field since I used NH. NH leadAyende RahienRecommendedKerberosity, You can try it.
Next, we need to create our own DbContext.
According to the official blogWalk throughIt will probably be written
Public Class EfDbContext: DbContext
{
Public DbSet < Hero > Heros { Get ; Set ;}
Public DbSet < Race > Races { Get ; & Nbs