zoukankan      html  css  js  c++  java
  • Entity Framework Code First 模式-建立一对多联系

    一、建立一对多联系

    使用的例子为Product与Category,一个种类(Product)对应多个商品(Product)

    1.外键列名默认约定

    在“一”这边的实体增加一个集合属性(public virtual ICollection<Product> Products { get; set; }),在“多”这边的实体增加两个属性(1.public int CategoryID { get; set; } 2.public virtual Category Category { get; set; })。其中Product实体的CategoryID要为Product实体的名字+ID(d)具体代码如下:

    public class Product
        {
            public int Id { get; set; }
            public string ProductName { get; set; }
            public decimal UnitPrice { get; set; }
            public int CategoryID { get; set; }
    
            public virtual Category Category { get; set; }
        }
     public class Category
        {
            public int Id { get; set; }
            public string CategoryName { get; set; }
    
            public virtual ICollection<Product> Products { get; set; }
        }

    运行后生成的表结构为:

    2.使用Data Annotations方式

     在“多”的一边的实体的所加的两个属性中的任何一个添加属性注解[ForeignKey("CatId")]

    以下演示一种:

    public int Id { get; set; }
            public string ProductName { get; set; }
            public decimal UnitPrice { get; set; }
            public int CatId { get; set; }
            [ForeignKey("CatId")]
            public virtual Category Category { get; set; }

    运行后结果为:

    注:ForeignKey("CatId")的CatId要与public int CatId { get; set; }里的CatId一样。

    3.Fluent API方式

    需要在DbEntity类中添加OnModelCreating方法

    public class Category
        {
            public int Id { get; set; }
            public string CategoryName { get; set; }
    
            public virtual ICollection<Product> Products { get; set; }
        }
     public class Product
        {
            public int Id { get; set; }
            public string ProductName { get; set; }
            public decimal UnitPrice { get; set; }
            public int CatId { get; set; }
            public virtual Category Category { get; set; }
        }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Product>()
                    .HasRequired(t => t.Category)
                    .WithMany(t => t.Products)
                    .HasForeignKey(d => d.CatId)
                    .WillCascadeOnDelete(false);//禁用级联删除,默认是开启的
            }

     运行后结果为:

  • 相关阅读:
    oracle客户端服务端字符集-解决乱码
    ORA-04089: 无法对 SYS 拥有的对象创建触发器
    ORA-01109:数据库未打开(解决)
    系统重装
    mybatis实现多表联合查询
    hibernate实现多表联合查询
    GitHub搭建博客过程
    mybatis&Hibernate区别
    IDEA搭建ssm框架测试衍生出的问题The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: D:Developjdk7jdk1.7.0_79in;
    IDEA创建maven项目jar更新缓慢问题
  • 原文地址:https://www.cnblogs.com/engineerlm/p/7604325.html
Copyright © 2011-2022 走看看