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一对一:一对多:多对多: 实例!!!!
学生表和课程表可以多对多 一个学生可以学多门课程 一门课程可以有多个学生: 多对多 *** 一个学生对应一个班级 一个班级对应多个学生: 一对多 *** 一个老师对应多个学生 多个学生对应一个老师:一 ...
随机推荐
- gcc/g++ 编译参数
1, -E(大写),预处理 例子:gcc -E test.cpp -o test.i 预处理,把程序里的#开头的替换掉,比如#include,然后生成test.i 2,-P(大写),去掉预处理生成的杂 ...
- MySql 触发器的新增、修改、删除的创建
MySql 触发器与SQL server 触发器不同: SQL Server 使用 inserted.deleted 代表被触发的数据. MySQL NEW代表触发后的新数据行,Old代表当前触发 ...
- linux 安装中文字体
工具/原料 centos6.5_x64 方法/步骤 centos6.5下使用下面命令进行安装 yum install -y fontconfig mkfontscale 使用fc-list ...
- redis5.0.4多实例安装
一.安装第一个实例 https://www.cnblogs.com/qq931399960/p/10584877.html 二.拷贝配置文件 cp /etc/redis.conf /etc/redis ...
- ValueError: too many values to unpack
Error msg: 执行: python manage,py makemigrations 报错:Value: too many values to unpack 问题: django第一次数据库迁 ...
- Windows API方式直接调用C#的DLL,支持多音字转拼音、Gzip解压缩、公式计算(VBA、C++、VB、Delphi甚至java都可以)
原始链接 https://www.cnblogs.com/Charltsing/p/DllExport.html 这两年,我在VBA应用方面一直有几大痛点:1.多音字转拼音:2.64位下的GZIP解压 ...
- form单选框
form中的单选框: var resultStartRadio = new Ext.form.RadioGroup({ id : 'resultStartRadio', name :"for ...
- 【刷题】牛客网看到的鹅厂ML面筋-部分问题RecSys相关
昨天下午六点半的电话面试,其实我已经有了一个不错的实习offer ,不是特别想去腾讯了,没有太怎么准备,接的电话. 整个面试15分钟,开始就是自我介绍,接着问项目,和上一段百度实习经历.问题大致如下: ...
- 五、Redis持久化配置
转载:[https://www.cnblogs.com/xingzc/p/5988080.html] Redis提供的持久化机制(RDB和AOF) Redis提供的持久化机制 Redis是一种面向“k ...
- 内核调试打印dump_stack
https://blog.csdn.net/dragon101788/article/details/9419175 在函数中加入dump_stack函数 需要包含的头文件: #include < ...