Entity Framework02-code first修改模型,迁移数据库

C#
本文总阅读量:
  1. 1. 添加属性
  2. 2. 使用Migrations修改数据库
  3. 3. 修改你的view对应的model
  4. 4. 修改对应的view展示
  5. 5. 如何展示新的信息
  6. 6. 自己创建新的model,展示想显示的信息

本文以asp.net mvc自己提供的身份验证为例

添加属性

Models\IdentityModels.csApplicationUser类下添加你想添加的属性,比如生日

1
public DateTime BirthDate { get; set; }

使用Migrations修改数据库

  • 由于已经改变了model的属性所以应该修改之前的数据库

  • 前往工具/NUGET/程序包管理器控制台

  • 输入Enable-Migrations初始化迁移

    Add-Migration "Birthdate" 添加名为Birthdate的迁移文件进你的工程

    Update-Database执行你的迁移文件更新数据库

修改你的view对应的model

Models\AccountViewModels.cs中找到RegisterViewModel类添加属性,当然也可以添加你想要的特性

1
public DateTime BirthDate { get; set; }

修改对应的view展示

1
2
3
4
5
<div class="input-field col s12 m3 l3">
<i class="material-icons prefix">date_range</i>
@Html.LabelFor(m => m.BirthDate)
@Html.TextBoxFor(m => m.BirthDate, new { @class = "datepicker" })
</div>

运行就能看到修改后的结果了

如何展示新的信息

  • 得到 UserId, 可以通过 ASP.NET Identity system

    1
    var currentUserId = User.Identity.GetUserId();
  • 实例化UserManager在ASP.Identity system命名空间下

  • 1
    var manager = new UserManager<MyUser>(new UserStore<MyUser>(new MyDbContext()));
  • 得到当前用户实例

    1
    var currentUser = manager.FindById(User.Identity.GetUserId());
  • 通过实例展现修改的信息

    1
    var birthdate = currentUser.BirthDate

自己创建新的model,展示想显示的信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class MyUser : IdentityUser
{
public virtual MyUserInfo MyUserInfo { get; set; }
}

public class MyUserInfo{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class MyDbContext : IdentityDbContext<MyUser>
{
public MyDbContext()
: base("DefaultConnection")
{
}
public System.Data.Entity.DbSet<MyUserInfo> MyUserInfo { get; set; }
}

Getting Profile information

  • When the User Logs in, you can display the profile information by doing the following

  • Get the current logged in UserId, so you can look the user up in ASP.NET Identity system

    • var currentUserId = User.Identity.GetUserId();
  • Instantiate the UserManager in ASP.Identity system so you can look up the user in the system

    • var manager = new UserManager(new UserStore(new MyDbContext()));
  • Get the User object

    • var currentUser = manager.FindById(User.Identity.GetUserId());
  • Get the profile information about the user

    • currentUser.MyUserInfo.FirstName