MVC数据建模例子

一.Database First

用”ADO.NET实体数据模型“生成模型

例题1

        public ActionResult Index()
        {
            m_user user = new m_user()
            {
                email = "litianpin@163.com",
                pwd = "123456",
                logintime = DateTime.Now
            };
            using (MeixinEntities1 db = new MeixinEntities1())
            {
                db.m_user.Add(user);
                db.SaveChanges();
            }
            return View();
        }


例题2

 public ActionResult Index()
        {
            using (MeixinEntities1 db = new MeixinEntities1())
            {
                var user = db.m_user.Find(1);
                //user.pwd = "654123";
                //db.SaveChanges();
                db.m_user.Remove(user);
                db.SaveChanges();
                //ViewBag.Email = user.email;
                //ViewBag.Pwd = user.pwd;
                //ViewBag.LogionTime = user.logintime;
            }
            return View();
        }

二.Code First

    public class m_order
    {
        public int id { get; set; }
        public string phone { get; set; }
        public string address { get; set; }
        public string message { get; set; }
        public string status { get; set; }
        public Nullable<DateTime> ordertime { get; set; }
        public double totel { get; set; }
        public virtual m_user m_user { get; set; }//virtual 表示启用EF框架延迟加载功能,尝试访问这些属性内容,将从数据库加载
    }

    public class m_user
    {
        public int id { get; set; }
        public string Email { get; set; }
        public string pwd { get; set; }
        public Nullable<DateTime> logintime { get; set; }
        public virtual ICollection<m_order> m_order { get; set; }
    }

    public class MeixinContext:DbContext
    {
        public DbSet<m_user> m_users { get; set; }
        public DbSet<m_order> m_order { get; set; }
    }


配置连接字符串

  <connectionStrings>
    <add name="MeixinContext" providerName="System.Data.SqlClient"  connectionString="Data Source=.;Initial Catalog=MeixinCodeFirst;Uid=sa;Pwd=123" />
  </connectionStrings>

        public ActionResult Index()
        {
            using (MeixinContext context = new MeixinContext())
            {
                var user = new m_user();
                user.id = 1;
                user.Email = "lyf@163.com";
                user.pwd = "123";
                user.logintime = DateTime.Now;
                context.m_users.Add(user);
                context.SaveChanges();
            }
            return View();
        

移除复数表明契约

    public class MeixinContext:DbContext
    {
        public DbSet<m_user> m_users { get; set; }
        public DbSet<m_order> m_order { get; set; }

        //以下为新增内容
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //移除复数表明契约
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }

//发现模型改动后,自动创建数据库
    public class InitDatabase:DropCreateDatabaseIfModelChanges<MeixinContext>
    {
        //数据库创建后添加初始化数据
        protected override void Seed(MeixinContext context)
        {
            m_user u = new m_user { Email = "kyf@163.com", pwd = "123", logintime = DateTime.Now};
            context.m_users.Add(u);
            context.SaveChanges();
            m_order o = new m_order { address = "上海某某地方 ", phone = "13212345678", message = "无消息"
                , m_user = u, ordertime = DateTime.Now, status = "未发货", totel = 135.8 };
            context.m_order.Add(o);
            context.SaveChanges();
        }
    }

public class MeixinContext:DbContext
    {
        public DbSet<m_user> m_users { get; set; }
        public DbSet<m_order> m_order { get; set; }

        //以下为新增代码,手动配置数据库
        public MeixinContext()
        {
            Database.SetInitializer(new InitDatabase());
        }
    }

        public ActionResult Index()
        {
            using (MeixinContext context = new MeixinContext())
            {
                var user = context.m_users.Find(1);
                ViewBag.Email = user.Email;
                ViewBag.Pwd = user.pwd;
                ViewBag.LoginTime = user.logintime;
            }
            return View();
        }


加载关联表的方式

1.延迟加载

public ActionResult Select1()
        {
            using (MeixinContext context = new MeixinContext()) {
                //通过邮箱查询该用户(主表)
                var user = (from u in context.m_users where u.Email == "lyf@163.com" select u).SingleOrDefault();
                var order=user.m_order.FirstOrDefault();
                if (order != null)
                {
                    ViewBag.phone = order.phone;
                }
            }
            return View();
        }

2.贪婪加载

/// <summary>
        /// 贪婪加载
        /// </summary>
        /// <returns></returns>u
        public ActionResult Select2()
        {
            string html = "<h2>全部用户订单</h2>";
            using (MeixinContext context = new MeixinContext())
            {
                //查询所有用户
                var users = context.m_users.Include("m_order");
                foreach (var u in users)
                {
                    html += "<h3>用户:" + u.Email + "<.h3>";
                    //查询用户的全部订单
                    foreach (var o in u.m_order)
                    {
                        html += "<h3>电话:" + o.phone + "</h3>";
                        //.....
                    }
                }
            }
            //输出文字内容,类似Response.Write的作用
            return Content(html);
        }

       //数据上下文对象初始化
        public MeixinContext()
        {
            //关闭延迟加载
            Configuration.LazyLoadingEnabled = false;
            Database.SetInitializer(new InitDatabase());
        }

3.贪婪加载

public ActionResult Select3()
        {
            string html = "<h2>用户及订单</h2>";
            using (MeixinContext context = new MeixinContext())
            {
                //通过邮箱查询该用户(主表)
                var user = (from u in context.m_users where u.Email == "lyf@163.com" select u).SingleOrDefault();
                html += "<h3>用户:lyf@163.com</h3>";
                //显示加载从表 Collection.Load获取集合或 Reference.Load 调用单个实体
                context.Entry(user).Collection("m_order").Load();
                //查询用户的全部订单
                foreach (m_order o in user.m_order)
                {
                    html += "<h3>电话:" + o.phone + "</h3>";
                    //.....
                }
            }
            return Content(html);
        }


















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值