Beispiel #1
0
        //添加单个Donator
        public static void CreateSingleDonator()
        {
            using (var context = new Context())
            //Context的实例用了using语句包装起来,这是因为DbContext实现了IDisposable接口。Dbcontext还包含了DbConnection的实例,该实例指向了具有特定连接字符串的数据库。在EF中合适地释放数据库连接和ADO.NET中同等重要
            {
                context.Database.CreateIfNotExists(); //如果数据库不存在则创建

                Donator donators = new Donator()
                {
                    Name = "单个", Amount = 50, DonateDate = new DateTime(2016, 4, 7)
                };

                context.Donators.Add(donators);
                context.SaveChanges();
            }
        }
Beispiel #2
0
        //一对多关系, 自定义配置链接
        public static void OneToManyCustom()
        {
            using (var context = new Context())
            {
                var donator = new Donator
                {
                    Amount     = 6,
                    Name       = "一对多时,添加的捐赠者",
                    DonateDate = DateTime.Parse("2016-7-6")
                };

                donator.PayWays.Add(new PayWay {
                    Name = "支付宝"
                });
                donator.PayWays.Add(new PayWay {
                    Name = "微信"
                });
                context.Donators.Add(donator);
                context.SaveChanges();
            }
        }