zoukankan      html  css  js  c++  java
  • Entity Framework 配置关系(1对1,1对0)

    Entity Framework 配置关系(1对1,1对0)

      实体之间的关系对应数据库表的关系,有1:0,1:1,1:N,N:N这几种。这里介绍1:0、1:1这两种配置关系。

      举例说明:Employee表示员工,Account表示通讯账号。有些员工使用通讯账号,但是有些员工不适用这些通讯账号。从员工的角度来观察,员工Employee与通讯账号Account之间的关系就是一个员工对应一个通讯账号(1:1),或者一个员工没有铜须你账号(1:0)。从通讯账号Account的角度来观察,一个通讯账号对应一个员工(1:1)。

    (1)实体类:Employee

    1 public class Employee
    2 {
    3     public int Id { get; set; }
    4 
    5     public string Name { get; set; }
    6 
    7     public virtual Account Account { get; set; }
    8 }

    (2)实体类:Account

     1 public class Account
     2 {
     3     public int Id { get; set; }
     4 
     5     public string UserName { get; set; }
     6 
     7     public string Password { get; set; }
     8 
     9     public virtual Employee Employee { get; set; }
    10 }

    (3)映射Employee

     1 public class EmployeeMap : EntityTypeConfiguration<Employee>
     2 {
     3     public EmployeeMap()
     4     {
     5         this.ToTable("Employee");
     6 
     7         this.HasKey(p => p.Id);
     8 
     9         this.Property(p => p.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    10         this.Property(p => p.Name).IsRequired().HasMaxLength(63);
    11     }
    12 }

    (4)映射Account

     1 public class AccountMap : EntityTypeConfiguration<Account>
     2 {
     3     public AccountMap()
     4     {
     5         this.ToTable("Account");
     6 
     7         this.HasKey(p => p.Id);
     8 
     9         this.Property(p => p.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    10         this.Property(p => p.UserName).IsRequired().HasMaxLength(63);
    11         this.Property(p => p.Password).IsRequired().HasMaxLength(63);
    12 
    13         this.HasRequired(m => m.Employee)
    14             .WithOptional(m => m.Account)
    15             .Map(m => m.MapKey("AccountId"))
    16             .WillCascadeOnDelete(true);
    17     }
    18 }

    (5)DbContext

     1 public class EntFraContext : DbContext
     2 {
     3     public IDbSet<Account> AccountSet { get; set; }
     4 
     5     public IDbSet<Employee> EmployeeSet { get; set; }
     6 
     7     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     8     {
     9         modelBuilder.Configurations.Add(new AccountMap());
    10         modelBuilder.Configurations.Add(new EmployeeMap());
    11 
    12         base.OnModelCreating(modelBuilder);
    13     }
    14 }

    分类: EntityFramework

  • 相关阅读:
    属于程序员的算法
    知乎:全栈工程师讨论
    盘点2015年前20款表现出色的免费开源软件
    qt学习之路
    ubuntu联网经常掉线的解决方法
    备份书签
    linux 命令行测试网速
    linux中判断ssh是否启动
    php heredoc 与 nowdoc
    php 双向队列类
  • 原文地址:https://www.cnblogs.com/grj001/p/12223624.html
Copyright © 2011-2022 走看看