读书人

Code First基础有关问题

发布时间: 2014-01-12 00:03:16 作者: rapoo

Code First基础问题
本帖最后由 hrabeyond 于 2014-01-10 09:32:42 编辑 小弟刚接触Code First,之前都是Database First的。。有个问题不太明白
写好了实体,写好了DBContext


public class TestTableContext : DbContext
{
public TestTableContext(string databaseName):base(databaseName){}

public DbSet<TestTable> TestTables { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//base.OnModelCreating(modelBuilder);
modelBuilder.Entity<TestTable>().ToTable("Table1");
//modelBuilder.Configurations.Add(new TestTableMap());
}
}

这样是不是就可以了呢?
然后我在程序里边用的时候:

static void Main(string[] args)
{
TestTable tt = new TestTable() { Name = "haha", age = 25 };

using (var context = new TestTableContext("ContextString"))
{
/*这里有问题
/*这里如果放开注释插入数据,会在SQLServer中新建一个数据库和一张表,并且插入数据,一切正常
/*这里如果注释掉,就是不插入数据,就不会创建数据库和表。*/
//context.TestTables.Add(tt);
context.SaveChanges();
}

Console.ReadKey();
}


想问下Code First就是这样的嘛?还是我哪儿少写什么东西了?
[解决办法]
是的,除非你开始添加数据,否则codefirst不会事先创建数据库。
[解决办法]
引用:
小弟刚接触Code First,之前都是Database First的。。有个问题不太明白
写好了实体,写好了DBContext

public class TestTableContext : DbContext
{
public TestTableContext(string databaseName):base(databaseName){}

public DbSet<TestTable> TestTables { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//base.OnModelCreating(modelBuilder);
modelBuilder.Entity<TestTable>().ToTable("Table1");
//modelBuilder.Configurations.Add(new TestTableMap());
}
}

这样是不是就可以了呢?
然后我在程序里边用的时候:

static void Main(string[] args)
{
TestTable tt = new TestTable() { Name = "haha", age = 25 };

using (var context = new TestTableContext("ContextString"))
{
/*这里有问题
/*这里如果放开注释插入数据,会在SQLServer中新建一个数据库和一张表,并且插入数据,一切正常
/*这里如果注释掉,就是不插入数据,就不会创建数据库和表。*/
//context.TestTables.Add(tt);
context.SaveChanges();
}

Console.ReadKey();
}


想问下Code First就是这样的嘛?还是我哪儿少写什么东西了?

如果只是想创建数据库直接用

context.Database.Create();

就行了

读书人网 >asp.net

热点推荐