私はEntityFrameworkのコードファーストを使用しています。
DataBaseName-SQLServerでデータベースを作成したい。
でweb.config
:
<configuration>
<connectionStrings>
<add name="DataContext"
providerName="System.Data.SqlClient"
connectionString="Data Source=USER\SQLEXPRESS;Initial Catalog=DataBaseName;Integrated Security=True;Pooling=False;User Instance = False" />
でglobal.asax
:
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
Database.SetInitializer(new DataContextInitializer());
}
DataContextInitializer
:
namespace CodeFirstMembershipSharp
{
public class DataContextInitializer : DropCreateDatabaseAlways<DataContext>
{
protected override void Seed(DataContext context)
{
MembershipCreateStatus Status;
Membership.CreateUser("Demo", "123456", null, null, null, true, out Status);
Roles.CreateRole("Admin");
Roles.AddUserToRole("Demo", "Admin");
}
}
}
DataContext
:
public class DataContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Bid>()
.HasRequired(a => a.Auction)
.WithMany()
.HasForeignKey(x => x.AuctionId).WillCascadeOnDelete(false);
modelBuilder.Entity<Bid>()
.HasRequired(a => a.User)
.WithMany()
.HasForeignKey(x => x.UserId).WillCascadeOnDelete(false);
}
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<Auction> Auctions { get; set; }
public DbSet<Page> Pages { get; set; }
public DbSet<Bid> Bids { get; set; }
}
ただし、データベースは作成されません。何を書くのを忘れましたか?