【问题标题】:When are foreign keys generated for related entities何时为相关实体生成外键
【发布时间】:2014-10-06 04:21:19
【问题描述】:

在使用实体框架(v6.1)时,我想知道何时在父/子实体之间设置外键关系。

假设我有一个代表宠物 Owner 的 Owner 实体。我还有一个 Pet 实体,它代表拥有 Owner 的宠物。创建新所有者时,我想创建一个或多个所有者实体拥有的宠物实体。

Owner newOwner = New Owner();
newOwner.LastName = "John";
newOwner.FirstName = "Doe";

Pet newPet1 = new Pet();
newPet1.Type = "Cat":
newPet1.Name = "Whiskers";

Pet newPet2 = new Pet();
newPet2 .Type = "Dog":
newPet2 .Name = "Fido";

// Add pets to Owner
newOwner.Add(newPet1);
newOwner.Add(newPet2);

// Add Owner to collection
Owners.Add(newOwner);
  1. 是否会自动为 Pet 实体填充外键(OwnerId)?假设 Owner 实体在实体模型中有一个主键,而 Pet 实体有 OwnerId 作为外键。
  2. 如何取回为每个实体生成的主键?
  3. 是否仅在调用 .SaveChanges() 后生成密钥?

【问题讨论】:

    标签: foreign-keys entity-framework-6


    【解决方案1】:

    你必须先用外键创建实体 然后你可以创建和保存实体

    将有多个 moh_areas 的第一个实体“区”

        public class District
        {
            public District()
            {
               List<MOH_area>  MOH_areasList = new List<MOH_area>();
            }
    
            [Key]
            [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
            public int dist_id { get; set; }
            public string dist_name { get; set; }
    
            public virtual ICollection<MOH_area> MOH_areas { get; set; }
        }
    
    Next entity
    
        public class MOH_area
        {
            public MOH_area() { }
    
            [Key]
            [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
            public int? moh_id { get; set; }
            public string moh_name { get; set; }
    
            public int dist_id { get; set; }
    
            [ForeignKey("dist_id")]
            public virtual District District { get; set; }
        }
    
    Now you can create and insert objects to db
    
        district dd= new destrict();
        dd.dist_name="abcdef";
        db.district.Add(dd);
        db.SaveChanges();
    
        MOH_area mo=new MOH_area();    // create and add many child elements
        mo.moh_name="my moh";
        mo.dist_id=dd.dist_id;  //  it has the id auto filled after the db insert
        db.MOH_area.add(mo);
        db.savechanges();
    
        MOH_area mo2=new MOH_area();    // create and add many child elements // no 2
        mo2.moh_name="my 2nd moh";
        mo2.dist_id=dd.dist_id;  //  it has the id auto filled after the db insert
        db.MOH_area.add(mo2);
        db.savechanges();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 2019-10-16
      • 1970-01-01
      相关资源
      最近更新 更多