zoukankan      html  css  js  c++  java
  • MVC EF Code First

    1 在Models里面创建类,用[Key]特性指定主键;

    2 在Model里面增加导航属性;

    3 在web.config里面增加连接字符串

    4 创建继承于DbContext的类

    5 创建Controller类,生成Index视图

    6 在Controller类的Index()里面,通过context.Database.CreateIfNotExist()


    //BookInfo.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;




    namespace CodeFirst.Models
    {
        public class BookInfo
        {
            [Key]
            public int BookId { get; set; }
            public string BookTitle { get; set; }
            public int TypeId { get; set; }


            public BookType BookType { get; set; }
        }

    }


    //BookType.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;


    namespace CodeFirst.Models
    {
        public class BookType
        {
             [Key]
            public int TypeId { get; set; }
            public string TypeTitle { get; set; }
            public ICollection<BookInfo> BookInfo { get; set; }
        }

    }

    //BooksContext

    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Web;


    namespace CodeFirst.Models
    {
        public class BooksContext:DbContext
        {
            public BooksContext():base("name=BooksContext")
            {
                
            }


            DbSet<BookInfo> BookInfo { get; set; }


            DbSet<BookType> BookType { get; set; }
        }

    }


    //web.config

     <connectionStrings>
        <add name="BooksContext" connectionString="server=.;database=books;uid=sa;pwd=Server2012" providerName="System.Data.SqlClient"/>

      </connectionStrings>

    //BooksController

    using CodeFirst.Models;
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;


    namespace CodeFirst.Controllers
    {
        public class BooksController : Controller
        {


            DbContext context = new BooksContext();
                
            //
            // GET: /Books/


            public ActionResult Index()
            {
                context.Database.CreateIfNotExists();
                context.SaveChanges();

                return View();
            }


        }
    }

  • 相关阅读:
    log4cpp
    互斥锁封装
    Educational Codeforces Round 37-F.SUM and REPLACE (线段树,线性筛,收敛函数)
    Codeforces 920E-Connected Components? (set,补图,连通块)
    Persistent Bookcase CodeForces
    P4390 [BOI2007]Mokia 摩基亚 (CDQ解决三维偏序问题)
    P3157 [CQOI2011]动态逆序对 (CDQ解决三维偏序问题)
    CDQ 分治解决和点对有关的问题
    洛谷 P2163 [SHOI2007]园丁的烦恼 (离线sort,树状数组,解决三维偏序问题)
    洛谷 P3469 [POI2008]BLO-Blockade (Tarjan,割点)
  • 原文地址:https://www.cnblogs.com/dxmfans/p/9434737.html
Copyright © 2011-2022 走看看