使用Code First 创建数据库

这是一个控制台程序,作用是通过Code First创建数据库.

1.添加EntityFrameWork的引用.

2.添加类 CodeFirstTest1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity; namespace ConsoleApplication1
{
public class CodeFirstTest1
{
public class Blog
{
public int blogID { get; set; }
public string title { get; set; }
public string content { get; set; }
public int columnID { get; set; }
public virtual Column column { get; set; }
}
public class Column
{
public int columnID { get; set; }
public int columnname { get; set; }
public virtual ICollection<Blog> blogs { get; set; }
} public class BlogContext : DbContext
{
public BlogContext()
: base("CodeFirstTest")
{
}
public DbSet<Blog> blogs { get; set; }
public DbSet<Column> columns { get; set; }
}
public class TestCodeFirst
{
public void Test()
{
using (var db = new BlogContext())
{
//向数据库添加记录
var column = new Column() { columnID = , columnname = };
db.columns.Add(column);
var blog = new Blog()
{
blogID = ,
title = "abc",
content = "test content",
columnID =
};
db.blogs.Add(blog); //保存记录,返回受影响的行数
int recordsAffected = db.SaveChanges();
Console.WriteLine("追加{0}记录成功", recordsAffected);
}
}
}
}
}

3.在主函数里面调用TestCodeFirst

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ConsoleApplication1.CodeFirstTest1.TestCodeFirst test = new ConsoleApplication1.CodeFirstTest1.TestCodeFirst(); test.Test();
}
}
}

4.改一下配置文件里面的连接字符串,指定名称.

  <connectionStrings>
<add name="CodeFirstTest" connectionString="data source=.;initial catalog=CodeFirstTest;integrated security=True;"
providerName="System.Data.SqlClient"/>
</connectionStrings>

5.调试

OK,这就生成了名称为CodeFirstTest的数据库了.

上一篇:iOS 中捕获程序崩溃日志 (2014-04-22 17:35:59)


下一篇:Java程序员应该知道的10个调试技巧