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);//禁用级联删除,默认是开启的
            }

     运行后结果为:

  • 相关阅读:
    理解Linux虚拟文件系统VFS
    Linux进程间通信(IPC)
    为 区域添加 Tag
    html 模板 swig 预编译插件 grunt-swig-precompile
    如何开发 Grunt 插件
    Web开发常见的漏洞
    CSS实现不固定宽度和高度的自动居中
    Sublime Text 前端插件推荐
    JavaScript 防止事件冒泡
    HTML标签篇
  • 原文地址:https://www.cnblogs.com/engineerlm/p/7604325.html
Copyright © 2011-2022 走看看