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

     运行后结果为:

  • 相关阅读:
    android PopupWindow的使用
    工作
    android StringUtils
    Android DrawableTextView图片文字居中显示
    android 布局使用GridView
    android 微信支付流程
    日记 2016.10.23 好好努力 不要放弃治疗!
    一、Python爬虫
    【Python工具】Excle 读写 (使用 xlrd 和 xlrt)
    Django中,图片显示问题--Django中静态文件处理方法指南
  • 原文地址:https://www.cnblogs.com/engineerlm/p/7604325.html
Copyright © 2011-2022 走看看