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

最新文章

  1. SQL Server 2008 R2 升级到 Service Pack 3后Report Builder启动不了
  2. 网站哀悼变灰代码集合 兼容所有浏览器的CSS变暗代码
  3. JAVA基础知识之Annotation
  4. CString std::string相互转换
  5. eclipse中java项目的build path详解
  6. JavaScript BOM 遗漏知识再整理;弹窗和记时事件;
  7. 关于常用的git命令列表
  8. iTunes无法验证服务器“s.mzstatic.com.”的身份
  9. kibana 日志查看界面
  10. phome_ecms_news 数据表字段解释(新闻系统模型-主表)
  11. ProjectManager Beta 2 项目管理器发布
  12. Android IPC机制全解析&lt;二&gt;
  13. css定位讲解
  14. 新购阿里云服务器ECS创建之后无法ssh连接的问题处理
  15. 基于hadoop的BI架构
  16. 使用Eclipse中的SVN提交代码遇到的问题
  17. 论文笔记:Deeper and Wider Siamese Networks for Real-Time Visual Tracking
  18. vant的坑
  19. poj3190 Stall Reservations
  20. python中matplotlib的颜色及线条控制

热门文章

  1. Silverlight及WPF中实现自定义BusyIndicator
  2. CF724D. Dense Subsequence[贪心 字典序!]
  3. WordPress基础:文章的自定义栏目的使用
  4. NVARCHAR 和VARCHAR区别和使用
  5. sphinx 全文搜索引擎安装与配置
  6. ASP.NET 学习小记 -- “迷你”MVC实现(1)
  7. TextField的文字距左边框的距离偏移
  8. ORACLE导入导出操作篇
  9. Smallest Difference(POJ 2718)
  10. BZOJ 1001: [BeiJing2006]狼抓兔子(最短路)
  11. Codefoces 277 E. Binary Tree on Plane
  12. blfs(systemd版本)学习笔记-编译安装openssh软件包
  13. ECharts 报表事件联动系列三:柱状图,饼状图实现联动
  14. 使用 requests 进行身份认证
  15. c++中的流
  16. UniGui之锱铢积累(仔细看这个文件)
  17. MySQL数据库命令大全
  18. JDBC程序优化--提取配置信息放到属性文件中
  19. Nodejs入门手记 (01):Hello World的WEB程序
  20. shell脚本监控Linux系统性能指标