zoukankan      html  css  js  c++  java
  • 使用 Fluent API 配置/映射属性和类型2

    1.将多个实体类映射到数据库中的一个表

       要将多个实体映射到一个数据库表需要满足:

       a. 两个实体必须是一对一关系

       b.两个实体共享一个主键

     1  public  class MyContext:DbContext
     2     {
     3         public MyContext()
     4             : base("test")
     5         { }
     6         protected override void OnModelCreating(DbModelBuilder modelBuilder)
     7         {
     8             modelBuilder.Entity<Person>()
     9                 .HasRequired(p => p.Detail)
    10                 .WithRequiredPrincipal();
    11         }
    12         public DbSet<Person> Persons { get; set; }
    13         public DbSet<PersonDetail> PersonDetails { get; set; }
    14 
    15     }
    16 
    17     [Table("Person")]
    18     public class Person
    19     {
    20         public int Id { get; set; }
    21         public string Name { get; set; }
    22         public bool Sex { get; set; }
    23         public PersonDetail Detail { get; set; }
    24     }
    25     [Table("Person")]
    26     public class PersonDetail
    27     {
    28         [Key,ForeignKey("Person")]
    29         public int Id { get; set; }
    30         public DateTime Birth { get; set; }
    31         public byte[] Photo { get; set; }
    32         public Person Person { get; set; }
    33     }
    34 }
    View Code

    2.将实体类型的 CLR 属性映射到数据库中的多个表

     1  public  class MyContext:DbContext
     2     {
     3         public MyContext()
     4             : base("test")
     5         { }
     6         protected override void OnModelCreating(DbModelBuilder modelBuilder)
     7         {
     8             modelBuilder.Entity<Person>()
     9                 .Map(p =>
    10                 {
    11                     p.Properties(t => new { t.Id, t.Name, t.Sex });
    12                     p.ToTable("Person");
    13                 })
    14                 .Map(p =>
    15                 {
    16                     p.Properties(t => new { t.Birth, t.Photo });
    17                     p.ToTable("PersonDetails2");
    18                 }
    19                 );
    20         }
    21         public DbSet<Person> Persons { get; set; } 
    22     }
    23 
    24     [Table("Person")]
    25     public class Person
    26     {
    27         public int Id { get; set; }
    28         public string Name { get; set; }
    29         public bool Sex { get; set; }  
    30         public DateTime Birth { get; set; }
    31         public byte[] Photo { get; set; }
    32     }
    View Code

  • 相关阅读:
    你爱的不爱你,转身是幸福
    按字节长度截取字符串(支持截取带HTML代码样式的字符串)
    存储过程操作类
    C# 拖动控件
    文件同步类
    c# 动态改变控件大小的方法
    虚拟世界改变现实 盛大兴建永恒之塔
    c#百钱买百鸡
    序列化类
    DLL专题之MFC规则库和扩展库
  • 原文地址:https://www.cnblogs.com/goodlucklzq/p/4612060.html
Copyright © 2011-2022 走看看