EF CodeFirst方式 Fluent Api配置
一.One-to-One Relationship【一对一关系】
两个表之间,只能由一个记录在另外一个表中。每一个主键的值,只能关联到另外一张表的一条或者零条记录。请记住,这个一对一的关系不是非常的普遍,并且大多数的一对一的关系,是商业逻辑使然,并且数据也不是自然地。缺乏这样一条规则,就是在这种关系下,你可以把两个表合并为一个表,而不打破正常化的规则。
为了理解一对一关系,我们创建两个实体,一个是User另外一个是UserProfile,一个User只有单个Profile,User表将会有一个主键,并且这个字段将会是UserProfile表的主键和外键。我们看下图:

创建两个实体,一个是User实体,另外一个是UserProfile实体。我们的User实体的代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace EF.Core.Data
{
public class User:BaseEntity
{
/// <summary>
/// 用户名
/// </summary>
public string UserName { get; set; } /// <summary>
/// 电子邮件
/// </summary>
public string Email { get; set; } /// <summary>
/// 密码
/// </summary>
public string Password { get; set; } /// <summary>
/// 导航属性--用户详情
/// </summary>
public virtual UserProfile UserProfile { get; set; }
}
}
UserProfile实体的代码快如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace EF.Core.Data
{
/// <summary>
/// 用户详情实体
/// </summary>
public class UserProfile:BaseEntity
{
/// <summary>
/// 姓
/// </summary>
public string FirstName { get; set; } /// <summary>
/// 名
/// </summary>
public string LastName { get; set; } /// <summary>
/// 地址
/// </summary>
public string Address { get; set; } /// <summary>
/// 导航属性--User
/// </summary>
public virtual User User { get; set; }
}
}
就像你看到的一样,上面的两个部分的代码块中,每个实体都使用彼此的实体,作为导航属性,因此你可以从任何实体中访问另外的实体。
使用Fluent Api配置Users实体:
using EF.Core.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace EF.Data.Mapping
{
public class UserMap:EntityTypeConfiguration<User>
{
public UserMap()
{
//配置主键
this.HasKey(s => s.ID); //给ID配置自动增长
this.Property(s => s.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
//配置字段
this.Property(s => s.UserName).IsRequired().HasColumnType("nvarchar").HasMaxLength(25);
this.Property(s => s.Email).IsRequired().HasColumnType("nvarchar").HasMaxLength(25);
this.Property(s => s.AddedDate).IsRequired();
this.Property(s => s.ModifiedDate).IsRequired();
this.Property(s => s.IP); //配置表
this.ToTable("User"); }
}
}
使用Fluent Api配置UserProfile实体
using EF.Core.Data;
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace EF.Data.Mapping
{
public class UserProfileMap:EntityTypeConfiguration<UserProfile>
{
public UserProfileMap()
{
this.HasKey(s=>s.ID); this.Property(s => s.FirstName).IsRequired();
this.Property(s => s.LastName).IsRequired();
this.Property(s => s.Address).HasMaxLength(100).HasColumnType("nvarchar").IsRequired(); this.Property(s => s.AddedDate).IsRequired();
this.Property(s => s.ModifiedDate).IsRequired();
this.Property(s => s.IP); //配置关系[一个用户只能有一个用户详情!!!]
this.HasRequired(s => s.User).WithRequiredDependent(s => s.UserProfile); this.ToTable("UserProfile"); }
}
}
现在,我们创建一个数据库上下文类EFDbContext,这个类继承DbContext类,在这个数据库上下文类中,我们重写OnModelCreating方法,这个OnModelCreating方法,在数据库上下文(EFDbContext)已经初始化的完成的时候,被调用,在OnModelCreating方法中,我们使用了反射,来为每个实体生成配置类。
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace EF.Data
{
public class EFDbContext:DbContext
{
public EFDbContext()
: base("name=DbConnectionString")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
{
var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(type => type.BaseType != null && type.BaseType.IsGenericType
&& type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach (var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
base.OnModelCreating(modelBuilder);
} }
}
}
二.One-to-Many Relationship【一对多关系】
主键表的一个记录,关联到关联表中,存在,没有,或者有一个,或者多个记录。这是最重要的也是最常见的关系
为了更好的理解一对多的关系,可以联想到电子商务系统中,单个用户可以下很多订单,所以我们定义了两个实体,一个是客户实体,另外一个是订单实体。我们看看下面的图片:

实体Customers代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace EF.Core.Data
{
public class Customer:BaseEntity
{
/// <summary>
/// 客户名称
/// </summary>
public string Name { get; set; } /// <summary>
/// 客户电子邮件
/// </summary>
public string Emial { get; set; } /// <summary>
/// 导航属性--Order
/// </summary>
public virtual ICollection<Order> Orders { get; set; }
}
}
实体Orders代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace EF.Core.Data
{
public class Order:BaseEntity
{
/// <summary>
/// 数量
/// </summary>
public byte Quantity { get; set; } /// <summary>
/// 价格
/// </summary>
public decimal Price { get; set; } /// <summary>
/// 客户ID
/// </summary>
public int CustomerId { get; set; } /// <summary>
/// 导航属性--Customer
/// </summary>
public virtual Customer Customer { get; set; }
}
}
你已经在上面的代码中注意到了导航属性,Customer实体有一个集合类型的Order属性,Order实体有一个Customer实体的导航属性,也就是说,一个客户可以有很多订单。
使用Fluent Api配置Customer实体
using EF.Core.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace EF.Data.Mapping
{
public class CustomerMap:EntityTypeConfiguration<Customer>
{
public CustomerMap()
{
this.HasKey(s => s.ID);
//properties
Property(t => t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(t => t.Name);
Property(t => t.Email).IsRequired();
Property(t => t.AddedDate).IsRequired();
Property(t => t.ModifiedDate).IsRequired();
Property(t => t.IP); //table
ToTable("Customers");
}
}
}
使用Fluent Api配置Orders实体
using EF.Core.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace EF.Data.Mapping
{
public class OrderMap:EntityTypeConfiguration<Order>
{
public OrderMap()
{
this.HasKey(s=>s.ID);
//fields
Property(t => t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(t => t.Quanatity).IsRequired().HasColumnType("tinyint");
Property(t => t.Price).IsRequired();
Property(t => t.CustomerId).IsRequired();
Property(t => t.AddedDate).IsRequired();
Property(t => t.ModifiedDate).IsRequired();
Property(t => t.IP); //配置关系【一个用户有多个订单,外键是CusyomerId】
this.HasRequired(s => s.Customer).WithMany(s => s.Orders).HasForeignKey(s => s.CustomerId).WillCascadeOnDelete(true); //table
ToTable("Orders");
}
}
}
上面的代码表示:用户在每个Order中是必须的,并且用户可以下多个订单,两个表之间通过外键CustomerId联系,我们使用了四个方法来定义实体之间的关系,Withmany方法允许多个。HasForeignKey方法表示哪个属性是Order表的外键,WillCascadeOnDelete方法用来配置是否级联删除。
三.Many-to-Many Relationship【多对多关系】
每条记录在两个表中,都可以关联到另外一个表中的很多记录【或者0条记录】。多对多关系,需要第三方的表,也就是关联表或者链接表,因为关系型数据库不能直接适应这种关系。
为了更好的理解多对多关系,我们想到,有一个选课系统,一个学生可以选秀很多课程,一个课程能够被很多学生选修,所以我们定义两个实体,一个是Syudent实体,另外一个是Course实体。我们来通过图表看看,多对多关系吧:

Student实体
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace EF.Core.Data
{
public class Student:BaseEntity
{
public string Name { get; set; }
public byte Age { get; set; }
public bool IsCurrent { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
}
Courses实体
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace EF.Core.Data
{
public class Course:BaseEntity
{
public string Name { get; set; }
public Int64 MaximumStrength { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
}
使用Fluent Api配置Student实体
using EF.Core.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace EF.Data.Mapping
{
public class StudentMap:EntityTypeConfiguration<Student>
{
public StudentMap()
{
//key
HasKey(t => t.ID); //property
Property(t => t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(t => t.Name);
Property(t => t.Age);
Property(t => t.IsCurrent);
Property(t => t.AddedDate).IsRequired();
Property(t => t.ModifiedDate).IsRequired();
Property(t => t.IP); //table
ToTable("Students"); //配置关系[多个课程,可以被多个学生选修]
//多对多关系实现要领:hasmany,hasmany,然后映射生成第三个表,最后映射leftkey,rightkey
this.HasMany(s => s.Courses).
WithMany(s => s.Students)
.Map(s => s.ToTable("StudentCourse").
MapLeftKey("StudentId").
MapRightKey("CourseId"));
}
}
}
上面的代码中,表示,一个学生可以选修多个课程,并且每个课程可以有很多学生,你知道,实现多对多的关系,我们需要第三个表,所以我们映射了第三个表,mapLeftkey和maprightkey定义了第三个表中的键,如果我们不指定的话,就会按照约定生成类名_Id的键。
使用Fluent Api配置Courses实体
using EF.Core.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace EF.Data.Mapping
{
public class CourseMap:EntityTypeConfiguration<Course>
{
public CourseMap()
{
this.HasKey(t => t.ID);//少了一行代码
//property
Property(t => t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(t => t.Name);
Property(t => t.MaximumStrength);
Property(t => t.AddedDate).IsRequired();
Property(t => t.ModifiedDate).IsRequired();
Property(t => t.IP); //table
ToTable("Courses");
}
}
}
出处:https://www.cnblogs.com/caofangsheng/p/5715876.html
EF CodeFirst方式 Fluent Api配置的更多相关文章
- EF CodeFirst 之 Fluent API
如何访问Fluent API: 在自定义上下文类中重写OnModelCreating方法,在方法内调用. 注:用法基本一样,配置类中的this就相当于modelBuilder.Entity<Pe ...
- 1.【使用EF Code-First方式和Fluent API来探讨EF中的关系】
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/relationship-in-entity-framework-using-code-firs ...
- 10.翻译系列:EF 6中的Fluent API配置【EF 6 Code-First系列】
原文链接:https://www.entityframeworktutorial.net/code-first/fluent-api-in-code-first.aspx EF 6 Code-Firs ...
- EF里的默认映射以及如何使用Data Annotations和Fluent API配置数据库的映射
I.EF里的默认映射 上篇文章演示的通过定义实体类就可以自动生成数据库,并且EF自动设置了数据库的主键.外键以及表名和字段的类型等,这就是EF里的默认映射.具体分为: 数据库映射:Code First ...
- EF——默认映射以及如何使用Data Annotations和Fluent API配置数据库的映射 02 (转)
EF里的默认映射以及如何使用Data Annotations和Fluent API配置数据库的映射 I.EF里的默认映射 上篇文章演示的通过定义实体类就可以自动生成数据库,并且EF自动设置了数据库 ...
- EF的默认映射以及如何使用Data Annotations和Fluent API配置数据库的映射
I.EF的默认映射 上节我们创建项目,通过定义实体类就可以自动生成数据库,并且EF帮我们自动设置了数据库的主键.外键以及表名和字段的类型等,这就是EF的默认映射.具体分为: 数据库映射:Code Fi ...
- Fluent API 配置
EF里实体关系配置的方法,有两种: Data Annotation方式配置 也可以 Fluent API 方式配置 Fluent API 配置的方法 EF里的实体关系 Fluent API 配置分为H ...
- Entity Framework 实体框架的形成之旅--Code First模式中使用 Fluent API 配置(6)
在前面的随笔<Entity Framework 实体框架的形成之旅--Code First的框架设计(5)>里介绍了基于Code First模式的实体框架的经验,这种方式自动处理出来的模式 ...
- 使用Fluent API 配置/映射属性和类型
Code First约定-Fluent API配置 使用Fluent API 配置/映射属性和类型 简介 通常通过重写派生DbContext 上的OnModelCreating 方法来访问Code F ...
随机推荐
- python基础学习笔记二之列表
1.列表 ①列表的创建: ②列表的查询(索引): ③列表的切片操作: 此处要注意到:返回索引0到3的元素,顾头不顾尾. ④列表的增加: s.append() #直接在结尾追加 s.insert() ...
- mysql-proxy实现读写分离
其中Amoeba for MySQL也是实现读写分离 环境描述:操作系统:CentOS6.5 32位主服务器Master:192.168.179.146从服务器Slave:192.168.179.14 ...
- HA集群heartbeat配置--Nginx
HA即(high available)高可用,又被叫做双机热备,用于关键性业务.简单理解就是,两台机器A和B,正常是A提供服务,B待命限制,当A宕机或服务宕掉,会切换至B机器继续提供服务.常用实现高可 ...
- 实现Windows程序的数据的绑定
1.创建DataSet对象 语法: DataSet 数据集对象 =new DataSet("数据集的名称字符串"); 语法中的参数是数据集的名称字符串,可以有,也可以没有.如 ...
- 大数据hadoop面试题2018年最新版(美团)
还在用着以前的大数据Hadoop面试题去美团面试吗?互联网发展迅速的今天,如果不及时更新自己的技术库那如何才能在众多的竞争者中脱颖而出呢? 奉行着"吃喝玩乐全都有"和"美 ...
- 初学MySQL基础知识笔记--01
本人初入博客园,第一次写博客,在今后的时间里会一点点的提高自己博客的水平,以及博客的排版等. 在今天,我学习了一下MySQL数据库的基本知识,相信关于MySQL的资料网上会有很多,所以我就不在这里复制 ...
- c# 动态实例化一个泛型类
动态实例化一个类,比较常见,代码如下 namespace ConsoleApp2 { public class MyClass { } } Type classType = Type.GetType( ...
- C语言第八次作业
一.PTA实验作业 题目1:统计一行文本的单词个数 1.本题PTA提交列表 2.设计思路 // 一个非空格和一个空格代表一个单词 char str[1000]: 存放一行文本 定义 I,j=0:用作循 ...
- Flask 视图
写个验证用户登录的装饰器:在调用函数前,先检查session里有没有用户 from functools import wraps from flask import session, abort de ...
- nyoj 鸡兔同笼
鸡兔同笼 时间限制:3000 ms | 内存限制:65535 KB 难度:1 描述 已知鸡和兔的总数量为n,总腿数为m.输入n和m,依次输出鸡和兔的数目,如果无解,则输出"No an ...