EF Code First一对一、一对多、多对多关联关系配置
1、EF Code First一对一关联关系
项目结构图:
实体类:
Account.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Northwind.App.Entities
{
public class Account
{
/// <summary>
/// 账户ID
/// </summary>
public int AccountID { get; set; } /// <summary>
/// 账户名
/// </summary>
public string AccountName { get; set; } /// <summary>
/// 密码
/// </summary>
public string Password { get; set; } /// <summary>
/// 用户信息
/// </summary>
public virtual User User { get; set; }
}
}

User.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Northwind.App.Entities
{
public class Account
{
/// <summary>
/// 账户ID
/// </summary>
public int AccountID { get; set; } /// <summary>
/// 账户名
/// </summary>
public string AccountName { get; set; } /// <summary>
/// 密码
/// </summary>
public string Password { get; set; } /// <summary>
/// 用户信息
/// </summary>
public virtual User User { get; set; }
}
}

实体映射类:
AccountMap.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations.Schema; using Northwind.App.Entities; namespace Northwind.App.Mapping
{
public class AccountMap : EntityTypeConfiguration<Account>
{
public AccountMap()
{
// Primary Key
this.HasKey(t => t.AccountID); // Properties
this.Property(t => t.AccountName).HasMaxLength(50);
this.Property(t => t.Password).HasMaxLength(100); // Table & Column Mappings
this.ToTable("Account");
this.Property(t => t.AccountID).HasColumnName("AccountID");
this.Property(t => t.AccountName).HasColumnName("AccountName");
this.Property(t => t.Password).HasColumnName("Password");
}
}
}

UserMap.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations.Schema; using Northwind.App.Entities; namespace Northwind.App.Mapping
{
public class UserMap : EntityTypeConfiguration<User>
{
public UserMap()
{
// Primary Key
this.HasKey(t => t.AccountID); // Properties
this.Property(t => t.AccountID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(t => t.UserName).HasMaxLength(50);
this.Property(t => t.Email).HasMaxLength(100); // Table & Column Mappings
this.ToTable("User");
this.Property(t => t.AccountID).HasColumnName("AccountID");
this.Property(t => t.UserName).HasColumnName("UserName");
this.Property(t => t.Email).HasColumnName("Email");
this.Property(t => t.RegisterDate).HasColumnName("RegisterDate"); // Relationships
this.HasRequired(t => t.Account)
.WithRequiredDependent(t => t.User);
}
}
}

NorthwindContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Data.Entity; using Northwind.App.Entities;
using Northwind.App.Mapping; namespace Northwind.App
{
public class NorthwindContext : DbContext
{
static NorthwindContext()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<NorthwindContext>());
} public DbSet<Account> Accounts { get; set; }
public DbSet<User> Users { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new AccountMap());
modelBuilder.Configurations.Add(new UserMap());
}
}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using Northwind.App.Entities; namespace Northwind.App
{
class Program
{
static void Main(string[] args)
{
using (NorthwindContext db = new NorthwindContext())
{
Account account = new Account { AccountName = "Test", Password = "1" };
db.Accounts.Add(account); User user = new User { AccountID = account.AccountID, UserName = "测试", Email = "test@126.com", RegisterDate = DateTime.Now };
db.Users.Add(user); db.SaveChanges();
}
}
}
}

代码运行后生成的数据库结构图:
2、EF Code First一对多关联关系
关联表:Product 产品表、Category分类表
关联关系:一个产品属于一个分类,一个分类可以有多个产品
实体代码:
Category.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Northwind.App.Entities
{
public class Category
{
/// <summary>
/// 分类ID
/// </summary>
public Guid CategoryID { get; set; } /// <summary>
/// 分类名称
/// </summary>
public string CategoryName { get; set; } /// <summary>
/// 产品
/// </summary>
public virtual ICollection<Product> Products { get; set; }
}
}

Product.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Northwind.App.Entities
{
public class Product
{
/// <summary>
/// 产品ID
/// </summary>
public Guid ProductID { get; set; } /// <summary>
/// 产品名称
/// </summary>
public string ProductName { get; set; } /// <summary>
/// 单价
/// </summary>
public decimal UnitPrice { get; set; } /// <summary>
/// 数量
/// </summary>
public Nullable<int> Quantity { get; set; } /// <summary>
/// 库存
/// </summary>
public Nullable<int> UnitsInStock { get; set; } /// <summary>
/// 产品类别ID
/// </summary>
public Guid CategoryID { get; set; } /// <summary>
/// 产品类别
/// </summary>
public virtual Category Category { get; set; }
}
}

实体映射类:
CategoryMap.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations.Schema; using Northwind.App.Entities; namespace Northwind.App.Mapping
{
public class CategoryMap : EntityTypeConfiguration<Category>
{
public CategoryMap()
{
// Primary Key
this.HasKey(t => t.CategoryID); // Properties
this.Property(t => t.CategoryID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(t => t.CategoryName).IsRequired()
.HasMaxLength(100); // Table & Column Mappings
this.ToTable("Category");
this.Property(t => t.CategoryID).HasColumnName("CategoryID");
this.Property(t => t.CategoryName).HasColumnName("CategoryName");
}
}
}

ProductMap.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations.Schema; using Northwind.App.Entities; namespace Northwind.App.Mapping
{
public class ProductMap : EntityTypeConfiguration<Product>
{
public ProductMap()
{
// Primary Key
this.HasKey(t => t.ProductID); // Properties
this.Property(t => t.ProductID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(t => t.ProductName).IsRequired()
.HasMaxLength(100);
this.Property(t => t.UnitPrice).HasPrecision(10, 2); // Table & Column Mappings
this.ToTable("Product");
this.Property(t => t.ProductID).HasColumnName("ProductID");
this.Property(t => t.ProductName).HasColumnName("ProductName");
this.Property(t => t.UnitPrice).HasColumnName("UnitPrice");
this.Property(t => t.Quantity).HasColumnName("Quantity");
this.Property(t => t.UnitsInStock).HasColumnName("UnitsInStock");
this.Property(t => t.CategoryID).HasColumnName("CategoryID"); // Relationships
this.HasRequired(t => t.Category)
.WithMany(t => t.Products)
.HasForeignKey(t => t.CategoryID)
.WillCascadeOnDelete(false);
}
}
}

NorthwindContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Data.Entity; using Northwind.App.Entities;
using Northwind.App.Mapping; namespace Northwind.App
{
public class NorthwindContext : DbContext
{
static NorthwindContext()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<NorthwindContext>());
} public DbSet<Account> Accounts { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new AccountMap());
modelBuilder.Configurations.Add(new UserMap());
modelBuilder.Configurations.Add(new CategoryMap());
modelBuilder.Configurations.Add(new ProductMap());
}
}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using Northwind.App.Entities; namespace Northwind.App
{
class Program
{
static void Main(string[] args)
{
using (NorthwindContext db = new NorthwindContext())
{
Category category = new Category { CategoryName = "手机数码" };
db.Categories.Add(category); Product product = new Product { CategoryID = category.CategoryID, ProductName = "IPhone5", UnitPrice = 5000m, Quantity = 100, UnitsInStock = 60 };
db.Products.Add(product); db.SaveChanges();
}
}
}
}

运行代码后生成的数据表:
http://www.cnblogs.com/libingql/archive/2013/01/31/2888201.html
EF Code First一对一、一对多、多对多关联关系配置的更多相关文章
- JPA级联(一对一 一对多 多对多)注解【实际项目中摘取的】并非自己实际应用
下面把项目中的用户类中有个:一对一 一对多 多对多的注解对应关系列取出来用于学习 说明:项目运行正常 问题类:一对多.一对一.多对多 ============一对多 一方的设置 @One ...
- Python进阶----表与表之间的关系(一对一,一对多,多对多),增删改查操作
Python进阶----表与表之间的关系(一对一,一对多,多对多),增删改查操作,单表查询,多表查询 一丶表与表之间的关系 背景: 由于如果只使用一张表存储所有的数据,就会操作数 ...
- mybatis 一对一 一对多 多对多
一对一 一对多 多对多
- 【EF Code First】 一对多、多对多的多重关系配置
这里使用用户表(User)和项目(Project)表做示例 有这样一个需求: 用户与项目的关系是:一个用户可以发多个项目,可以参加多个项目,而项目可以有多个参与成员和一个发布者 [其中含1-n和n-n ...
- 使用NHibernate(7)-- 一对一 && 一对多 && 多对多
1, 一对一. 对于数据量比较大的时候,考虑查询的性能,肯能会把一个对象的属性分到两个表中存放:比如用户和用户资料,经常使用的一般是Id和用户名,用户资料(学校,籍贯等)是不经常被查询的,所以就会分成 ...
- day 69-70 一对一 一对多 多对一联表查询
day 69 orm操作之表关系,多对多,多对一 多对一/一对多, 多对多{类中的定义方法} day69 1. 昨日内容回顾 1. 单表增删改查 2. 单表查询API 返回QuerySet对象的: 1 ...
- JPA 一对一 一对多 多对一 多对多配置
1 JPA概述 1.1 JPA是什么 JPA (Java Persistence API) Java持久化API.是一套Sun公司 Java官方制定的ORM 方案,是规范,是标准 ,sun公司自己并没 ...
- SQLAlchemy_定义(一对一/一对多/多对多)关系
目录 Basic Relationship Patterns One To Many One To One Many To Many Basic Relationship Patterns 基本关系模 ...
- MySQL一对一:一对多:多对多: 实例!!!!
学生表和课程表可以多对多 一个学生可以学多门课程 一门课程可以有多个学生: 多对多 *** 一个学生对应一个班级 一个班级对应多个学生: 一对多 *** 一个老师对应多个学生 多个学生对应一个老师:一 ...
随机推荐
- hbase 过滤器 rowfilter
HBase为筛选数据提供了一组过滤器,通过这个过滤器可以在HBase中的数据的多个维度(行,列,数据版本)上进行对数据的筛选操作,也就是说过滤器最终能够筛选的数据能够细化到具体的一个存储单元格上(由行 ...
- Spring Boot使用Maven打包替换资源文件占位符
在Spring Boot开发中,通过Maven构建项目依赖是一件比较舒心的事,可以为我们省去处理冲突等大部分问题,将更多的精力用于业务功能上.近期在项目中,由于项目集成了其他外部系统资源文件,需要根据 ...
- Redis入门教程(一)
一.NoSQL概述 1.什么是NoSQL NoSQL,泛指非关系型的数据库.随着互联网web2.0网站的兴起,传统的关系数据库在应付web2.0网站,特别是超大规模和高并发的SNS类型的web2.0纯 ...
- Git常用命令使用大全
1.查看.添加.提交.删除.找回,重置修改文件 git help <command> # 显示command的help git show # 显示某次提交的内容 git show $id ...
- c# 创建excel表头及内容
主要通过ajax调用函数Getinfo 1.定义表dh DataTable dh = new DataTable(); 2.创建表头 public void CreateCol(string Colu ...
- Windows Server 2008远程桌面默认端口更改方法
win2008远程桌面端口默认是用的是3389端口,但是由于安全考虑,经常我们安装好系统后一般都会考虑把原来的3389端口更改为另外的端口. 本文以改为端口为25608商品为例,讲解一下具体操作过程. ...
- c语言static关键字的理解
static 一.概述 在c语言中static恰当的使用能让程序更加完美,细节上的严谨,代码会更好,也更利于程序的维护与扩展. 而static使用灵活,且又有两种完全无关的用法,所以整理总结一下. 二 ...
- 码农也来关注下经济问题<美元加息>对我们的影响
昨天凌晨三点,美联储宣布加息25个基点,这是今年美联储第四次加息,也是2015年12月份以来的第九次加息.基准利率又上调了25个基点,全球市场又要开始惴惴不安了. 要知道上一次美国基准利率上调25个基 ...
- Mysql原理与优化
原文:https://mp.weixin.qq.com/s__biz=MzI4NTA1MDEwNg==&mid=2650763421&idx=1&sn=2515421f09c1 ...
- 老白关于rac性能调优的建议(10gRAC)
RAC应用设计方面需要在底层做很有设计.虽然ORACLE的售前人员总是说RAC的扩展性是透明的,只要把应用分到不同的节点,就可以平滑的扩展系统能力了.而事实上,RAC的CACHE FUSION机制决定 ...