Entity Framework01-code first建立一个新数据库

C#
本文总阅读量:
  1. 1. 建立model
  2. 2. 建立上下文(Context)
  3. 3. 读取 存入数据
  4. 4. 接下来我会分别介绍各个部分

建立model

编写.net class建立model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Blog 
{
public int BlogId { get; set; }
public string Name { get; set; }

public virtual List<Post> Posts { get; set; }
}

public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }

public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
  • 类中带id的会自动标志成主键
  • 两个导航属性 (Blog.Posts and Post.Blog) virtual,这是entity framework懒加载( Lazy Loading
  • )的特征,懒加载值得是这些属性内容会自动从数据库中加载出来

建立上下文(Context)

添加引用

1
using System.Data.Entity;

建立数据库上下文,继承自DbContext

1
2
3
4
5
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}

DbSet代表数据库中的表,上下文中存储就是关系表

读取 存入数据

存入

1
2
3
4
var tmpBlog = new Blog() { Name = "luox78's blog" };
var db = new BloggingContext();
db.Blogs.Add(tmpBlog);
db.SaveChanges();

读取

1
2
3
4
5
6
var obj = db.Blogs.Where(blog => blog.BlogId == 1);
foreach (var blog in obj)
{
Console.WriteLine(blog.Name);
}
//luox78's blog

数据在哪儿?

  • Visual Studio 2010数据库一般建在 local SQL Express
  • Visual Studio 2012以上一般在 LocalDb.aspx)
  • 数据库命名是项目名加上建立的上下文名字

https://luox78.github.io/images/entity1.png

执行完写入之后数据已经进入数据库

https://luox78.github.io/images/entity2.png

接下来我会分别介绍各个部分

原文:Entity Framework Code First to a New Database.aspx)

翻译:luox78