aspnetcore2.0-entity framework

EntityFramework是微软推荐的ORM框架。好的,下面直接进入主题:

migration

由于ORM框架要保证内存中的数据结构和数据库中的数据结构完全一样,所以每当内存中的数据结构发生变化需要migration,以保证一致:

dotnetcore ef 的migration命令

1
2
3
4
5
6
7
In Visual Studio, use the Package Manager Console to scaffold a new migration
for these changes and apply them to the database:
PM> Add-Migration [migration name]
PM> Update-DatabaseAlternatively, you can scaffold a new migration and
apply it from a command prompt at your project directory:
> dotnet ef migrations add [migration name]
> dotnet ef database update

primary key

By default, the Entity Framework interprets a property that’s named ID or classnameID as the primary key.
如果是composition key, ef for asp.net core只能通过fluent api来实现:

lang=csharp
1
2
3
4
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<UserHome>().HasKey(new[] { nameof(UserHome.HomeID), nameof(UserHome.UserID) });
}