• 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();
            }


        }
    }

  • 相关阅读:
    treeview十八般武艺,js选择和绑定权限树
    开源WebOS
    公交车路线查询系统后台数据库设计
    网页信息抓取
    一步一步打造WebIM(3)——性能测试
    WebBrowser介绍——Javascript与C++互操作
    .NET文档生成工具ADB[更新至2.3]
    一步一步打造WebIM(4)——Comet的特殊之处
    在SQL Server中对视图进行增删改
    开源企业即时通讯和在线客服
  • 原文地址:https://www.cnblogs.com/dxmfans/p/9434737.html
Copyright © 2020-2023  润新知