您的位置:首页 > 其它

EntityFramework Core 学习笔记 —— 创建模型

2016-08-03 22:31 525 查看
原文地址:https://docs.efproject.net/en/latest/modeling/index.html

前言:

EntityFramework 使用一系列的约定来从我们的实体类细节创建模型。我们可以钦定一些额外的映射配置来添加、重写实体类的哪些细节应该被这些约定所发现。

这篇文章讲述了一些无论模型被存储在哪种关系型数据库中都可以生效的配置项。DataBase Provider 也同样可以针对某一种数据存储启用指定的配置项。更多相关文档请查看:Database Providers


This article covers configuration that can be applied to a model targeting any data store and that which can be applied when targeting any relational database. Providers may also enable configuration that is specific to a particular data store. For documentation on provider specific configuration see the the Database Providers section.

这段我感觉翻译的有问题,所以提供原文给大家参考


在这一章节中,你可以找到关于下面列出的约定以及配置项的信息:

下面的东西都是链接到不同小节的,我慢慢来翻译

包含与排除类型

包含与排除属性

设置 Key (主键)

Generated Properties

Required/optional properties

Maximum Length

Concurrency Tokens

Shadow Properties

Relationships

Indexes

Alternate Keys

Inheritance

Backing Fields

Relational Database Modeling

Table Mapping

Column Mapping

Data Types

Primary Keys

Default Schema

Computed Columns

Sequences

Default Values

Indexes

Foreign Key Constraints

Alternate Keys (Unique Constraints)

Inheritance (Relational Database)


提示!

你可以在 GitHub 上面找到这篇文章的示例代码


配置的方法

Flunt API

我们可以在我们自己实现的上下文中通过使用
ModelBuilder
提供的 API 重写
OnModelCreating
方法来配置我们的模型类。这是最具有超级牛力的配置方法,并且,通过这种方式,我们无需修改我们的模型类。Flunt API 具有最高优先级并且会重写约定以及 data annotions。

class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.IsRequired();
}
}

Data Annotations

我们同样可以通过在我们的实体类或者其属性上面附加一些特性(attributes,比如 Data Annotations)。Data Annotations 会重写约定,但是会被 Fluent API 重写定义。

public class Blog
{
public int BlogId { get; set; }
[Required]
public string Url { get; set; }
}

我的笔记

Entity Framework教程(第二版)这篇博客中,hystar 大神提到了使用继承
EntityTypeConfiguration<EntityType>
的方式来添加映射,然而这种方法现在在 .Net Core 中无法使用了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: