コード例 #1
0
ファイル: One2OneClass.cs プロジェクト: zealoussnow/OneCode
        // 使用personAddress插入新的person
        public static void InsertPersonWithPersonAddress()
        {
            using (EFO2OEntities context = new EFO2OEntities())
            {
                Person person = new Person()
                {
                    FirstName = "Lingzhi",
                    LastName ="Sun"
                };

                // PersonAddress中的PersonID将是27因为它依赖于person.PersonID
                PersonAddress personAddress = new PersonAddress()
                {
                    PersonID = 100,
                    Address = "Shanghai",
                    Postcode = "200021"
                };

                // 设置navigation属性 (一对一)
                person.PersonAddress = personAddress;

                context.AddToPerson(person);

                try
                {
                    Console.WriteLine("Inserting a person with "
                        + "person address");

                    context.SaveChanges();

                    Query();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
コード例 #2
0
ファイル: One2OneClass.cs プロジェクト: zealoussnow/OneCode
        // 更新一个现存的person
        public static void UpdatePerson()
        {
            using (EFO2OEntities context = new EFO2OEntities())
            {
                Person person = new Person();

                person.PersonID = 1;

                context.AttachTo("Person", person);

                person.LastName = "Chen";

                // 将外键设置为空
                person.PersonAddress = null;

                try
                {
                    Console.WriteLine("Modifying Person 1's LastName to {0}"
                        + ", and PersonAddress to null", person.LastName);

                    context.SaveChanges();

                    Query();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }