EntityFramework Core 学习系列(一)Creating Model
EntityFramework Core 学习系列(一)Creating Model
Getting Started
使用Command Line 来添加 Package
dotnet add package Microsoft.EntityFrameworkCore.SqlServer 使用 -v 可以指定相应包的版本号。
使用dotnet ef 命令
需要在.csproj 文件中包含下面引用
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0"/>
</ItemGroup>
Creating a Model
Fluent API
在继承至 DbContext 的子类中,重载 OnModelCreating() 方法进行Fluent API 的配置。
public class MyDbContext : DbContext
{
//...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TEntity>()
.Property(b => b.Url)
.IsRequired();
//...
}
//...
}
Data Annotation
或者可以使用数据注解直接在实体中进行配置:
public class Blogs
{
public string BlogName { get; set; }
[Required]
public string Url { get; set; }
}
关于配置的顺序规范,
Fluent API > Data Annotations > Conventions
Include & Exclude
有下列三种情况类或实体会被包含:
- By convention, types that are exposed in
DbSetproperties on your context are included in your model. - Types that are mentioned in the
OnModelCreatingmethod are also included. - Any types that are found by recursively exploring the navigation properties of discovered types are also included in the model.
你可以通过 Data Annotation 或者 Fluent API 来 排除包含,示例如下:
//Data Annotations Example Below:
public class Blogs
{
public int BlogId { get; set;}
public BlogAuthor BlogAuthors { get; set;}
}
[NotMapped]
public class BlogAuthor
{
public string FirstName { get; set;}
//...
}
//Fluent API Example Below:
public class MyDbContext : DbContext
{
public DbSet<Blog> Blogs { get; set;}
protected override OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Ignore<BlogAuthor>();
}
}
public class Blogs
{
public int BlogId { get; set;}
public BlogAuthor BlogAuthors { get; set;}
}
public class BlogAuthor
{
public string FirstName { get; set;}
//...
}
当然除了可以排出/包含类之外, 还可以自己配置相应的属性如下:
//Data Annotations Example Below:
public class Blogs
{
public int BlogId { get; set;}
public BlogAuthor BlogAuthors { get; set;}
[NotMapped]
public DateTime BlogAddedTime { get; set;}
}
//Fluent API Example Below:
public class MyDbContext : DbContext
{
public DbSet<Blog> Blogs { get; set;}
protected override OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Ignore(b => b.BlogAddedTime);
}
}
public class Blogs
{
public int BlogId { get; set;}
public BlogAuthor BlogAuthors { get; set;}
public DateTime BlogAddedTime { get; set;}
}
Key
关于EF Core 中的Key, 按照规范,如果一个属性命名为Id 或者 以Id结尾的都会被配置成该实体的主键。比如下面的这个:
public class TestClass
{
public int Id { get; set; }
//or
public int MyId { get; set; }
}
或者你可以按照 Data Annotation 或者 Fluent API 来进行配置:
// Data Annotations
public class Car
{
[Key]
public string CarLicense { get; set; }
public string CarFrameCode { get; set;}
}
//Fluent API
//...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Car>()
.HasKey(c => c.CarLicense);
}
//...
// Multiple Properties to the key ,复合主键的配置只能用Fluent API
modelBuilder.Entity<Car>()
.HasKey(c => new { c.CarLicense, c.CarFrameCode });
Generated Values
中文应该是叫值的自动生成吧,我也不清楚。EF Core 上 有三种 Value Generation Pattern。分别是
No Value Generation
No value generation means that you will always supply a valid value to be saved to the database. This valid value must be assigned to new entities before they are added to the context.
值不自动生成,每个属性的值都需要指定,添加。这个我理解的意思应该是你保存到数据库里面的值,每个必须是有效的,并且需要指定。
Value Generated on Add
Value generated on add means that a value is generated for new entities.
Depending on the database provider being used, values may be generated client side by EF or in the database. If the value is generated by the database, then EF may assign a temporary value when you add the entity to the context. This temporary value will then be replaced by the database generated value during
SaveChanges().If you add an entity to the context that has a value assigned to the property, then EF will attempt to insert that value rather than generating a new one. A property is considered to have a value assigned if it is not assigned the CLR default value (
nullforstring,0forint,Guid.EmptyforGuid, etc.).属性的值在 添加到数据库时自动添加。
Value Generated on Add or Update
Value generated on add or update means that a new value is generated every time the record is saved (insert or update).
Like
value generated on add, if you specify a value for the property on a newly added instance of an entity, that value will be inserted rather than a value being generated. It is also possible to set an explicit value when updating.属性的值在 添加到数据库或者更新时自动添加。
当当看着上面这三个,我其实并不知道这三个到底是什么意思,接下来会用例子来演示一下这些具体意思,以及使用规范。
By convention, primary keys that are of an integer or GUID data type will be setup to have values generated on add. All other properties will be setup with no value generation.(当主键为 Interger 或者 GUID类型事,该主键的值会自动生成。)
下面用实例来模拟一下:
我们新建一个实体 Blogs 如下:
//Entity Blog
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
// Program.cs
using (var db = new BookDbContext())
{
if (!db.Blogs.Any())
{
var blog = new Blog
{
Url = "Https://q.cnblogs.com"
};
db.Blogs.AddRange(blog);
db.SaveChanges();
}
}
直接用在Program 用using 来演示效果,由于我们之前说到的主键为 Integer 类型的会自动生成值,所以数据库中的值大家可想而知,就是下面这个
下面是用Data Annotation(数据注解)来演示的,也可以用Fluent API:
No Value Generation
如果我们不想让它自动生成的话呢,也有办法。向下面这样:
public class Blog
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int BlogId { get; set; }
public string Url { get; set; }
}
我在 BlogId 上加上 DatabaseGeneratedOption.None 之后,我们再重新运行上面的程序,发现数据库的值如下所示:
为什么是 0 的原因呢,其实上面已经解释过了:就是下面这句话
A property is considered to have a value assigned if it is not assigned the CLR default value (
nullforstring,0forint,Guid.EmptyforGuid, etc.). CLR 的默认值。
Fluent API 版本
modelBuilder.Entity<Blog>()
.Property(b => b.BlogId)
.ValueGeneratedNever();
Value Generated on Add
比如我们还想在 Blog 实体里面加一个 更新时间 UpdateTime 属性
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
[DataGenerated(DatabaseGeneratedOption.Identity)]
public DateTime UpdateTime { get; set;}
}
当我们配置成上面这样,然后直接 dotnet run 时,发现程序报错了。
Unhandled Exception: Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> Microsoft.Data.Sqlite.SqliteException: SQLite Error 19: 'NOT NULL constraint failed: Blogs.UpdateTime'.
在Setting Explicit Value 中在OnModelCreating 中配置,使其自动生成,但是本地我使用SQLite 时无法自动生成,报错。具体使用如下
modelBuilder.Entity<Blog>()
.Property(p => p.UpdateTime)
.HasDefaultValueSql("CONVERT(date, GETDATE())");
Fluent API 版本
modelBuilder.Entity<Blog>()
.Property(b => b.UpdateTime)
.ValueGeneratedOnAdd();
Value generated on add or update (Data Annotations)
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime LastUpdated { get; set; }
}
Fulent API 版本
modelBuilder.Entity<Blog>()
.Property(b => b.LastUpdated)
.ValueGeneratedOnAddOrUpdate();
下面记录一下 dotnet ef 命令的使用
dotnet ef migrations add name
dotnet ef database update
dotnet ef migrations remove
dotnet ef database drop
EntityFramework Core 学习系列(一)Creating Model的更多相关文章
- ASP.NET Core学习系列
.NET Core ASP.NET Core ASP.NET Core学习之一 入门简介 ASP.NET Core学习之二 菜鸟踩坑 ASP.NET Core学习之三 NLog日志 ASP.NET C ...
- EntityFramework Core 学习笔记 —— 创建模型
原文地址:https://docs.efproject.net/en/latest/modeling/index.html 前言: EntityFramework 使用一系列的约定来从我们的实体类细节 ...
- EntityFramework Core 学习扫盲
0. 写在前面 1. 建立运行环境 2. 添加实体和映射数据库 1. 准备工作 2. Data Annotations 3. Fluent Api 3. 包含和排除实体类型 1. Data Annot ...
- Net core学习系列(一)——Net Core介绍
一.什么是Net Core .NET Core是适用于 windows.linux 和 macos 操作系统的免费.开源托管的计算机软件框架,是微软开发的第一个官方版本,具有跨平台 (Windows. ...
- EntityFramework Core 学习笔记 —— 添加主键约束
原文地址:https://docs.efproject.net/en/latest/modeling/keys.html Keys (primary) Key 是每个实体例的主要唯一标识.EF Cor ...
- 【.Net Core 学习系列】-- EF Core 实践(Code First)
一.开发环境: VS2015, .Net Core 1.0.0-preview2-003156 二解决方案: 新建项目: File --> New --> Project --> ...
- 【.Net Core 学习系列】-- EF Core实践(DB First)
一.开发环境: VS2015, .Net Core 1.0.0-preview2-003156 二.准备数据: CREATE DATABASE [Blogging]; GO USE [Blogging ...
- Net core学习系列(八)——Net Core日志
一.简介# 日志组件,作为程序员使用频率最高的组件,给程序员开发调试程序提供了必要的信息.ASP.NET Core中内置了一个通用日志接口ILogger,并实现了多种内置的日志提供器,例如 Conso ...
- Net core学习系列(四)——Net Core项目执行流程
"跨平台"后的ASP.Net Core是如何接收并处理请求的呢? 它的运行和处理机制和之前有什么不同?本章从"宏观"到"微观"地看一下它的结 ...
随机推荐
- Maven学习笔记一
maven是apache下的一个开源项目,是纯java开发,并且只是用来管理java项目的. Maven好处 1.普通的传统项目,包含jar包,占用空间很大.而Maven项目不包含jar包,所以占用空 ...
- string和c_str()使用时的坑
先看一段代码和它的运行结果: 看到结果了么这个运行的结果和我们理解的是不会有差距.对于经验丰富的开发者可能会微微一笑,但是对于一个刚刚学习的人就开始疑惑了.这里主要说两个问题: 1.声明了一个stri ...
- 测试与发布(Beta版本)
评分基准: 按时交 - 有分(测试报告-10分,发布说明-10分,展示博客-10分),检查的项目包括后文的两个方面 测试报告(基本完成5分,根据完成质量加分,原则上不超过满分10分) 发布说明(基本完 ...
- 团队作业7——第二次项目冲刺(Beta版本12.08)
项目每个成员的进展.存在问题.接下来两天的安排. 已完成的内容:完成了排行榜的测试.上传头像功能的原型设计.界面优化 计划完成的内容:上传头像功能开发.测试.头像裁剪原型设计 每个人的工作 (有wor ...
- Django SNS 微博项目开发
1.功能需求 一个人可以follow很多人 一个用户如果发了新weibo会自动推送所有关注他的人 可以搜索.关注其它用户 可以分类关注 用户可以发weibo, 转发.收藏.@其它人 发微博时可选择公开 ...
- android批量打包
http://blog.csdn.net/johnny901114/article/details/48714849
- 成功案例分享:raid5两块硬盘掉线数据丢失恢复方法
1. 故障描述 本案例是HP P2000的存储vmware exsi虚拟化平台,由RAID-5由10块lT硬盘组成,其中6号盘是热备盘,由于故障导致RAID-5磁盘阵列的两块盘掉线,表现为两块硬 ...
- video与audio的使用
HTML5 DOM 为 <audio> 和 <video> 元素提供了方法.属性和事件. 这些方法.属性和事件允许您使用 JavaScript 来操作 <audio> ...
- Mego(05) - 创建模型
Mego框架使用一组约定来基于CLR类来构建模型.您可以指定其他配置来补充和/或覆盖通过约定发现的内容. 这里需要强调的我们EF不同的是框架只支持数据注释的语法来构建模型,后期只有通过其他接口才能更改 ...
- 泛型的 typeof
static void Main(string[] args) { TestTypeOf<string>(); Console.ReadKey(); } static void TestT ...

