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

     运行后结果为:

  • 相关阅读:
    将数字转化为字符串
    给定一列数字将其平移n位
    判断回文数的问题
    c语言链表逆序的问题
    python中类属性和实例属性的区别
    python中__repr__()方法
    python中模块和包
    flask如何写一个model
    遍历文件夹下excel文件并且写入一个新excel
    python统计任务耗时
  • 原文地址:https://www.cnblogs.com/engineerlm/p/7604325.html
Copyright © 2011-2022 走看看