Google Code Prettify

[MVC]Code First Example



User
using System;

namespace TokenTest.Models {
    public class User {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
        public Guid Salt { get; set; }

        public int RoleId { get; set; }
        public virtual Role Role { get; set; }
    }
}


Role
using System.Collections.Generic;

namespace TokenTest.Models {
    public class Role {
        public int RoleId { get; set; }
        public string Name { get; set; }

        public ICollection User { get; set; }
    }
}


DbContext
using System.Data.Entity;

    namespace TokenTest.Models {
        public class TokenDbContext : DbContext {
            public TokenDbContext()
                : base("name=TokenDbConnection") {
            }

            public virtual DbSet≪User> User { get; set; }
            public virtual DbSet≪Role> Role { get; set; }

            protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            }
        }
    }



因為我在 TokenDbContext 的 base 中,設定 name = TokenDbContext 所以在 web.config 的資料庫連線中要設定:


<configuration>
  <connectionStrings>
    <add name="TokenDbConnection" connectionString="Data Source=localhost;Initial Catalog=MvcTestDb;User ID=xxxxx;Password=xxxxx;Pooling=false;"
      providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>