您的位置:首页 > 数据库

MVC自动生成数据库【Code-FIrst方式】

2016-04-29 11:39 357 查看
一般我们写好实体之后,配置好数据上下文对象,还有在配置文件中改好连接字符串之后。
还不能生成数据库,自动生成数据库,有两步关键步骤:

1. Enable Migrations

2. Update-database

执行玩第二步之后,就自动生成了数据库。

------------------------------------实例----------------------------------------------------------------
//实体:

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

namespace PagingAndSortingInMvc.Entities
{
public class EmployeeMaster
{
[Key]
public string ID { get; set; }

[Required(ErrorMessage="请输入员工名字")]
public string Name { get; set; }

[Required(ErrorMessage="请输入手机号码")]
public string PhoneNumber { get; set; }

[Required(ErrorMessage="请输入Email")]
public string Email { get; set; }

[Required(ErrorMessage= "请输入薪水")]
public decimal Salary { get; set; }

}
}

-------------------------------------------------------------------------------------------------------------

创建的数据上下文类:

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

namespace PagingAndSortingInMvc.Models
{
public class ApplicationDbContext:DbContext
{
public ApplicationDbContext()
: base("name=ConnectionString")
{ }

public DbSet<EmployeeMaster> Employees { get; set; }
}
}

-----------------------------------------------------------------------------------------------------

配置文件中的数据库连接字符串:

<connectionStrings>
<add name="ConnectionString" connectionString="server=.;database=PageAndSortDB;uid=sa;pwd=Password_1" providerName="System.Data.SqlClient"/>
</connectionStrings>

----------------------------------------------------------------------------------------------------------------------------------------------------------

设置这些之后,编译一下项目:

就运行:
1. Enable Migrations----------会生成一个类文件【Configuration.cs】,改一下AutomaticMigrationsEnabled 属性为true

namespace PagingAndSortingInMvc.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;

internal sealed class Configuration : DbMigrationsConfiguration<PagingAndSortingInMvc.Models.ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}

protected override void Seed(PagingAndSortingInMvc.Models.ApplicationDbContext context)
{
// This method will be called after migrating to the latest version.

// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}

2. Update-database ---执行玩这个之后,在数据库中就生成了我们配置好的数据库,数据表

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: