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一对一、一对多、多对多关联关系配置的更多相关文章

  1. JPA级联(一对一 一对多 多对多)注解【实际项目中摘取的】并非自己实际应用

    下面把项目中的用户类中有个:一对一  一对多  多对多的注解对应关系列取出来用于学习      说明:项目运行正常 问题类:一对多.一对一.多对多 ============一对多 一方的设置 @One ...

  2. Python进阶----表与表之间的关系(一对一,一对多,多对多),增删改查操作

    Python进阶----表与表之间的关系(一对一,一对多,多对多),增删改查操作,单表查询,多表查询 一丶表与表之间的关系 背景: ​ ​ ​  ​ ​ 由于如果只使用一张表存储所有的数据,就会操作数 ...

  3. mybatis 一对一 一对多 多对多

    一对一 一对多 多对多

  4. 【EF Code First】 一对多、多对多的多重关系配置

    这里使用用户表(User)和项目(Project)表做示例 有这样一个需求: 用户与项目的关系是:一个用户可以发多个项目,可以参加多个项目,而项目可以有多个参与成员和一个发布者 [其中含1-n和n-n ...

  5. 使用NHibernate(7)-- 一对一 && 一对多 && 多对多

    1, 一对一. 对于数据量比较大的时候,考虑查询的性能,肯能会把一个对象的属性分到两个表中存放:比如用户和用户资料,经常使用的一般是Id和用户名,用户资料(学校,籍贯等)是不经常被查询的,所以就会分成 ...

  6. day 69-70 一对一 一对多 多对一联表查询

    day 69 orm操作之表关系,多对多,多对一 多对一/一对多, 多对多{类中的定义方法} day69 1. 昨日内容回顾 1. 单表增删改查 2. 单表查询API 返回QuerySet对象的: 1 ...

  7. JPA 一对一 一对多 多对一 多对多配置

    1 JPA概述 1.1 JPA是什么 JPA (Java Persistence API) Java持久化API.是一套Sun公司 Java官方制定的ORM 方案,是规范,是标准 ,sun公司自己并没 ...

  8. SQLAlchemy_定义(一对一/一对多/多对多)关系

    目录 Basic Relationship Patterns One To Many One To One Many To Many Basic Relationship Patterns 基本关系模 ...

  9. MySQL一对一:一对多:多对多: 实例!!!!

    学生表和课程表可以多对多 一个学生可以学多门课程 一门课程可以有多个学生: 多对多 *** 一个学生对应一个班级 一个班级对应多个学生: 一对多 *** 一个老师对应多个学生 多个学生对应一个老师:一 ...

随机推荐

  1. python不能调试的原因

    最近有一个python项目,打开项目不能登录,想调试一下看看为什么,发现不能调试了,郁闷了,搞了半天,发现是进程里有多个python.exe,结束掉就好了.

  2. 详解Tomcat的连接数和线程池

    转: https://www.cnblogs.com/kismetv/p/7806063.html#t11 前言 在使用tomcat时,经常会遇到连接数.线程数之类的配置问题,要真正理解这些概念,必须 ...

  3. PS教程:抠透明冰块

    1.打开我们需要用到的素材,ctrl+a全选,ctrl+c复制 2.接下来给图层添加一个图层蒙版,按alt键点击图层蒙版,看到它变成白色了 3.ctrl+v,把刚才复制好的图粘贴进来 4.接着ctrl ...

  4. 数据结构排序算法插入排序Java实现

    public class InsertDemo { public static void main(String args[]) { int[] sort ={4,2,1,3,6,5,9,8,10,7 ...

  5. JS 时间字符串与时间戳之间的转换

    1.当前时间换时间戳 var timestamp = parseInt(new Date().getTime()/1000); // 当前时间戳 document.write(timestamp); ...

  6. Python基础:数据类型-数字(5)

    在Python中,所有的数据类型都是类,每一个变量都是类的实例. Python中有6种标准数据类型:数字(Number).字符串(String).列表(List).元组(Tuple).集合(Sets) ...

  7. cocos creator入门

    前面的话 Cocos Creator 是一个完整的游戏开发解决方案,包括了 cocos2d-x 引擎的 JavaScript 实现,以及快速开发游戏所需要的各种图形界面工具.Cocos Creator ...

  8. ElementUI DatePicker 日期选择器控制选择时间范围

    选择今天以及今天之后的日期 <el-date-picker v-model="value1" type="date" placeholder=" ...

  9. odoo 配置文件参数大全

    odoo 数据库配置文件参数 [options] ; addons模块的查找路径 addons_path = E:\GreenOdoo8.0\source\openerp\addons ; 管理员主控 ...

  10. Wiki leaks files backup

    Wiki leaks files backup 来源  http://ftp.icm.edu.pl/packages/incoming/torrent/ Index of /packages/inco ...