EF Code First关系规则及配置
1、一对多关系
关系表:
Category 分类表
Product 产品表
分类与产品之间的一对多关系
1>、产品实体类不指定外键属性
Domain中类定义:
Category.cs

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 using System.ComponentModel.DataAnnotations;
7
8 namespace Northwind.Domain.Entities
9 {
10 public class Category
11 {
12 /// <summary>
13 /// 分类ID
14 /// </summary>
15 public int CategoryID { get; set; }
16
17 /// <summary>
18 /// 分类名称
19 /// </summary>
20 public string CategoryName { get; set; }
21
22 /// <summary>
23 /// 描述
24 /// </summary>
25 public string Description { get; set; }
26
27 /// <summary>
28 /// 图片
29 /// </summary>
30 public byte[] Picture { get; set; }
31
32 /// <summary>
33 /// 产品
34 /// </summary>
35 public virtual ICollection<Product> Products { get; set; }
36 }
37 }

Product.cs

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace Northwind.Domain.Entities
7 {
8 public class Product
9 {
10 /// <summary>
11 /// 产品ID
12 /// </summary>
13 public int ProductID { get; set; }
14
15 /// <summary>
16 /// 产品名称
17 /// </summary>
18 public string ProductName { get; set; }
19
20 /// <summary>
21 /// 单价
22 /// </summary>
23 public decimal UnitPrice { get; set; }
24
25 /// <summary>
26 /// 库存
27 /// </summary>
28 public int UnitsInStock { get; set; }
29
30 /// <summary>
31 /// 是否售完
32 /// </summary>
33 public bool Discontinued { get; set; }
34
35 /// <summary>
36 /// 产品分类
37 /// </summary>
38 public virtual Category Category { get; set; }
39 }
40 }

CategoryMap.cs

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 using System.Data.Entity.ModelConfiguration;
7 using System.ComponentModel.DataAnnotations;
8
9 using Northwind.Domain.Entities;
10
11 namespace Northwind.Domain.Mapping
12 {
13 public class CategoryMap : EntityTypeConfiguration<Category>
14 {
15 public CategoryMap()
16 {
17 this.ToTable("dbo.Category");
18 this.HasKey(t => t.CategoryID);
19
20 this.Property(t => t.CategoryName).IsRequired().HasMaxLength(15);
21 this.Property(t => t.Picture).HasColumnType("image");
22 }
23 }
24 }

ProductMap.cs

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 using System.Data.Entity.ModelConfiguration;
7 using System.ComponentModel.DataAnnotations;
8
9 using Northwind.Domain.Entities;
10
11 namespace Northwind.Domain.Mapping
12 {
13 public class ProductMap : EntityTypeConfiguration<Product>
14 {
15 public ProductMap()
16 {
17 this.ToTable("dbo.Product");
18 this.HasKey(t => t.ProductID);
19
20 this.Property(t => t.ProductName).IsRequired().HasMaxLength(50);
21 this.Property(t => t.UnitPrice).HasPrecision(18, 2);
22 }
23 }
24 }

Data中类定义:
NorthwindContext.cs

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 using System.Data.Entity;
7
8 using Northwind.Domain.Entities;
9 using Northwind.Domain.Mapping;
10
11 namespace Northwind.Data
12 {
13 public class NorthwindContext : DbContext
14 {
15 public DbSet<Category> Categories { get; set; }
16 public DbSet<Product> Products { get; set; }
17
18 protected override void OnModelCreating(DbModelBuilder modelBuilder)
19 {
20 modelBuilder.Configurations.Add(new CategoryMap());
21 modelBuilder.Configurations.Add(new ProductMap());
22 }
23 }
24 }

App中类定义:
Program.cs

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 using Northwind.Data;
7 using Northwind.Domain.Entities;
8
9 using System.Data.Entity;
10
11 namespace Northwind.App
12 {
13 class Program
14 {
15 static void Main(string[] args)
16 {
17 // 数据模型改变,删除数据库重新创建。
18 Database.SetInitializer(new DropCreateDatabaseIfModelChanges<NorthwindContext>());
19
20 Category c = new Category() { CategoryName = "电子数码" };
21
22 Product p = new Product() { ProductName = "笔记本电脑", UnitPrice = 4500.00m, Category = c, UnitsInStock = 100, Discontinued = false };
23 using (NorthwindContext db = new NorthwindContext())
24 {
25 db.Categories.Add(c);
26 db.Products.Add(p);
27
28 db.SaveChanges();
29 }
30
31 Console.WriteLine("Finish");
32 Console.ReadKey();
33 }
34 }
35 }

运行之后生成的数据库结构

2>、产品实体类中指定外键属性
修改Domain中Product.cs代码:

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace Northwind.Domain.Entities
7 {
8 public class Product
9 {
10 /// <summary>
11 /// 产品ID
12 /// </summary>
13 public int ProductID { get; set; }
14
15 /// <summary>
16 /// 产品名称
17 /// </summary>
18 public string ProductName { get; set; }
19
20 /// <summary>
21 /// 单价
22 /// </summary>
23 public decimal UnitPrice { get; set; }
24
25 /// <summary>
26 /// 库存
27 /// </summary>
28 public int UnitsInStock { get; set; }
29
30 /// <summary>
31 /// 是否售完
32 /// </summary>
33 public bool Discontinued { get; set; }
34
35 /// <summary>
36 /// 分类ID
37 /// </summary>
38 public int CategoryID { get; set; }
39
40 /// <summary>
41 /// 产品分类
42 /// </summary>
43 public virtual Category Category { get; set; }
44 }
45 }

运行之后生成的数据库中表结构如下:

默认的外键规则:[Target Type Key Name], [Target Type Name] + [Target Type Key Name], 或者 [Navigation
Property Name] + [Target Type Key Name]。
3>、使用Data Annotations指定外键属性

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 using System.ComponentModel.DataAnnotations;
7
8 namespace Northwind.Domain.Entities
9 {
10 public class Product
11 {
12 /// <summary>
13 /// 产品ID
14 /// </summary>
15 public int ProductID { get; set; }
16
17 /// <summary>
18 /// 产品名称
19 /// </summary>
20 public string ProductName { get; set; }
21
22 /// <summary>
23 /// 单价
24 /// </summary>
25 public decimal UnitPrice { get; set; }
26
27 /// <summary>
28 /// 库存
29 /// </summary>
30 public int UnitsInStock { get; set; }
31
32 /// <summary>
33 /// 是否售完
34 /// </summary>
35 public bool Discontinued { get; set; }
36
37 /// <summary>
38 /// 分类ID
39 /// </summary>
40 public int CategoryID { get; set; }
41
42 /// <summary>
43 /// 产品分类
44 /// </summary>
45 [ForeignKey("CategoryID")]
46 public virtual Category Category { get; set; }
47 }
48 }

4>、使用Fluent指定外键属性

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 using System.Data.Entity.ModelConfiguration;
7 using System.ComponentModel.DataAnnotations;
8
9 using Northwind.Domain.Entities;
10
11 namespace Northwind.Domain.Mapping
12 {
13 public class ProductMap : EntityTypeConfiguration<Product>
14 {
15 public ProductMap()
16 {
17 // Primary Key
18 this.HasKey(t => t.ProductID);
19
20 // Properties
21 this.Property(t => t.ProductName).IsRequired().HasMaxLength(50);
22 this.Property(t => t.UnitPrice).HasPrecision(18, 2);
23
24 // Table & Column Mappings
25 this.ToTable("dbo.Product");
26 this.Property(t => t.ProductID).HasColumnName("ProductID");
27 this.Property(t => t.ProductName).HasColumnName("ProductName");
28 this.Property(t => t.UnitPrice).HasColumnName("UnitPrice");
29 this.Property(t => t.UnitsInStock).HasColumnName("UnitsInStock");
30 this.Property(t => t.Discontinued).HasColumnName("Discontinued");
31 this.Property(t => t.CategoryID).HasColumnName("CategoryID");
32
33 // Relationships
34 this.HasRequired(t => t.Category)
35 .WithMany(t => t.Products)
36 .HasForeignKey(t => t.CategoryID)
37 .WillCascadeOnDelete(false);
38 }
39 }
40 }

5>、示例代码附件
以上示例代码附件,并补充Product与Category及Supplier的两个外键关联。
二、多对多关系
表说明:
用户表:User
角色表:Role
用户与角色多对多,一个用户可以属于多个角色,一个角色可以有多个用户。
Domain中User.cs

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace Northwind.Domain.Entities
7 {
8 public class User
9 {
10 /// <summary>
11 /// 用户ID
12 /// </summary>
13 public int UserID { get; set; }
14
15 /// <summary>
16 /// 用户名
17 /// </summary>
18 public string UserName { get; set; }
19
20 /// <summary>
21 /// 密码
22 /// </summary>
23 public string Password { get; set; }
24
25 /// <summary>
26 /// 角色
27 /// </summary>
28 public ICollection<Role> Roles { get; set; }
29 }
30 }

Role.cs

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace Northwind.Domain.Entities
7 {
8 public class Role
9 {
10 /// <summary>
11 /// 角色ID
12 /// </summary>
13 public int RoleID { get; set; }
14
15 /// <summary>
16 /// 角色名称
17 /// </summary>
18 public string RoleName { get; set; }
19
20 /// <summary>
21 /// 用户
22 /// </summary>
23 public virtual ICollection<User> Users { get; set; }
24 }
25 }

UserMap.cs

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 using System.Data.Entity.ModelConfiguration;
7 using System.ComponentModel.DataAnnotations;
8
9 using Northwind.Domain.Entities;
10
11 namespace Northwind.Domain.Mapping
12 {
13 public class UserMap : EntityTypeConfiguration<User>
14 {
15 public UserMap()
16 {
17 // Primary Key
18 this.HasKey(t => t.UserID);
19
20 // Properties
21 this.Property(t => t.UserName).IsRequired().HasMaxLength(50);
22 this.Property(t => t.Password).IsRequired().HasMaxLength(50);
23
24 // Table & Column Mappings
25 this.ToTable("dbo.User");
26 this.Property(t => t.UserID).HasColumnName("UserID");
27 this.Property(t => t.UserName).HasColumnName("UserName");
28 this.Property(t => t.Password).HasColumnName("Password");
29
30 // Relationships
31 this.HasMany(t => t.Roles)
32 .WithMany(t => t.Users)
33 .Map(t => t.MapLeftKey("RoleID").MapRightKey("UserID"));
34 }
35 }
36 }

RoleMap.cs

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 using System.Data.Entity.ModelConfiguration;
7 using System.ComponentModel.DataAnnotations;
8
9 using Northwind.Domain.Entities;
10
11 namespace Northwind.Domain.Mapping
12 {
13 public class RoleMap : EntityTypeConfiguration<Role>
14 {
15 public RoleMap()
16 {
17 // Primary Key
18 this.HasKey(t => t.RoleID);
19
20 // Properties
21 this.Property(t => t.RoleName).IsRequired().HasMaxLength(50);
22
23 // Table & Column Mappings
24 this.ToTable("dbo.Role");
25 this.Property(t => t.RoleID).HasColumnName("RoleID");
26 this.Property(t => t.RoleName).HasColumnName("RoleName");
27
28 // Relationships
29 this.HasMany(t => t.Users)
30 .WithMany(t => t.Roles)
31 .Map(t => t.MapLeftKey("UserID").MapRightKey("RoleID"));
32 }
33 }
34 }

Data中NorthwindContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Data.Entity; using Northwind.Domain.Entities;
using Northwind.Domain.Mapping; namespace Northwind.Data
{
public class NorthwindContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CategoryMap());
modelBuilder.Configurations.Add(new ProductMap());
modelBuilder.Configurations.Add(new SupplierMap());
modelBuilder.Configurations.Add(new UserMap());
modelBuilder.Configurations.Add(new RoleMap());
}
}
}

运行成功后生成的数据表:

三、一对一关系
http://www.cnblogs.com/libingql/archive/2012/03/28/2421084.html
EF Code First关系规则及配置的更多相关文章
- EF Code First 学习笔记:约定配置 Data Annotations+Fluent API
要更改EF中的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面;还有一个就 ...
- 【EF Code First】CodeFirst初始配置
1,在Nuget管理中下载EntityFramework 2,配置文件中添加数据库配置 <connectionStrings> <add name="DefaultConn ...
- [转载]EF Code First 学习笔记:约定配置
要更改EF中的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面;还有一个就 ...
- EF Code First 学习笔记:约定配置
要更改EF中的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面;还有一个就 ...
- 【转】EF Code First 学习笔记:约定配置
要更改EF中的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面;还有一个就 ...
- EF Code First 学习笔记:约定配置(转)
要更改EF中的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面;还有一 ...
- EF Code First教程-02 约定配置
示例: public class Phone { [Key] //主键 public int Id { get; set; } [Required] //不能为空 [MinLength(),MaxLe ...
- EF Code First 一对多、多对多关联,如何加载子集合?
应用场景 先简单描述一下标题的意思:使用 EF Code First 映射配置 Entity 之间的关系,可能是一对多关系,也可能是多对多关系,那如何加载 Entity 下关联的 ICollectio ...
- EF Code First学习笔记
EF Code First学习笔记 初识Code First EF Code First 学习笔记:约定配置 Entity Framework 复杂类型 Entity Framework 数据生成选项 ...
随机推荐
- SwaggerAPI注解详解,以及注解常用参数配置
注解 @Api: 作用在类上,用来标注该类具体实现内容.表示标识这个类是swagger的资源 . 参数: tags:可以使用tags()允许您为操作设置多个标签的属性,而不是使用该属性. descri ...
- casbin-权限管理
概要 权限管理几乎是每个系统或者服务都会直接或者间接涉及的部分. 权限管理保障了资源(大部分时候就是数据)的安全, 权限管理一般都是和业务强关联, 每当有新的业务或者业务变化时, 不能将精力完全放在业 ...
- 影响Linux发展的四位天才黑客
影响Linux发展的四位天才黑客 相信大家对 Linux 再熟悉不过了.我们都知道 Linux继承自 Unix,但其实他们上一代还有一个 Multics.从最早的 Multics 发展到最早版本的 L ...
- 003_python中key为中文的处理
由于统计域名资产信息时,部门名称是中文的,但是还需要用这个部门名称进行字符的匹配运算,但不进行转换处理的话,它会报以下的错误: 解决方法如下: # -*- coding: utf-8 -*- all_ ...
- 2018-2019 ACM-ICPC, Asia East Continent Finals I. Misunderstood … Missing(dp)
题目链接: http://codeforces.com/gym/102056/problem/I 题意: 人物有l两个属性分别是$A,D$ 每个回合人物$A\pm D$ 每个回合有三个选择分别是: 1 ...
- java基础-jdk工具包
1. 标准工具 这些工具都是JDK提供的,通常都是长期支持的工具,JDK承诺这些工具比较好用.不同系统.不同版本之间可能会有差异,但是不会突然就有一个工具消失. 1.1 基础包 (extcheck, ...
- MVC多张图片上传
1. 在视图中要写 @using (Html.BeginForm("AddProductaction","Admin",FormMethod.Post, new ...
- Flutter内置ICON
由于有时打不开flutter的icon官网 https://material.io/tools/icons/?style=baseline 截图存下icon 如果看不清 Ctrl + 恢复Ctr ...
- Virtual DOM 系列三:Diff算法
DOM操作是昂贵的,为了减少DOM操作,才有了Virtual DOM.而Virtual DOM的关键就是通过对比新旧vnode,找出差异部分来更新节点.对比的关键算法就是Diff算法. 历史由来: d ...
- canvas学习笔记,实用知识点总结(上)
本博客是本人日常学习笔记,作为重要知识点的总结记录,随笔风格可能更倾向于个人的学习习惯和方式,若对您有帮助十分荣幸,若存在问题欢迎互相学习探讨,前端小白一枚在此恭候. 一.基本使用规则 1.创建画布 ...