对象之间的数据库中没有创建链接

时间:2018-04-18 17:43:06

标签: .net entity-framework

我有两个从edmx模型生成的类与数据库同步:

public partial class Activity
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Activity()
        {
            this.People = new HashSet<Person>();
        }

        public System.Guid ActivityId { get; set; }
        public string Name { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Person> People { get; set; }
    }
}

public partial class Person
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Person()
        {
            this.Activities = new HashSet<Activity>();
        }

        public System.Guid PersonID { get; set; }
        public string Name { get; set; }
        public Nullable<int> Age { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Activity> Activities { get; set; }
    }

但是当我尝试将Person类型的对象与Activity链接时,没有任何内容进入PeopleActivities表,它是空的。也没有错误。有关违反唯一主要约束的错误,但我注释掉People = ...然后运行程序,然后取消注释此代码并且没有错误但也没有效果。

    Person p1 = new Person { PersonID = new Guid("F9012DB1-E639-4831-AC69-FECBE1F59F0A"), Age = 15, Name = "Roman" },
    p2 = new Person { PersonID = new Guid("73EE7313-F1C4-4312-A2F9-8224F6807A02"), Age = 23, Name = "Szczepan" },
    p3 = new Person { PersonID = new Guid("F0DF22A9-B884-4036-9678-9D0D8E1459F6"), Age = 20, Name = "Katarzyna" };
    using (StudentsActivitiesCorrect context = new StudentsActivitiesCorrect())
    {
        context.People.AddOrUpdate(person => person.PersonID, new Person[] { p1, p2, p3 });
        context.SaveChanges();
    }

    Activity a1 = new Activity { ActivityId = new Guid("0ADE2334-CF52-4868-9D92-D08C4B029958"), Name = "swimming", People = new HashSet<Person> { p1, p2 } },
        a2 = new Activity { ActivityId = new Guid("148E4CAF-65A8-4E26-A8BD-BB44911B2A03"), Name = "bikinga", People = new HashSet<Person> { p1, p2, p3 } },
        a3 = new Activity { ActivityId = new Guid("84B4F160-A8F6-4B4F-AE4F-0E192799122B"), Name = "boxing", People = new HashSet<Person> { p2 } };

    using (StudentsActivitiesCorrect context = new StudentsActivitiesCorrect())
    {
        context.Activities.AddOrUpdate(activity => activity.ActivityId, new Activity[] { a1, a2, a3 });
        context.SaveChanges();
    }

为什么会这样,为什么这些对象没有在关联表中链接?

0 个答案:

没有答案