何时为相关实体生成外键

时间:2014-09-11 18:00:56

标签: foreign-keys entity-framework-6

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

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

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)?假设所有者实体在实体模型中具有主键,并且Pet实体将OwnerId作为外键。
  2. 如何才能找回为每个实体生成的主键?
  3. 是否仅在调用.SaveChanges()之后生成密钥?

1 个答案:

答案 0 :(得分:0)

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

第一个实体'区'这将有多个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();