using System;
namespace ConsoleApp
{
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World!");
}
}
}
在 ConsoleApp 目录运行 dnx run 验证程序是否正确运行,运行 dnx ef 验证EF安装是否成功。
using System.Collections.Generic;
using System.IO;
using Microsoft.Data.Entity;
using Microsoft.Extensions.PlatformAbstractions;
namespace ConsoleApp
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var path = PlatformServices.Default.Application.ApplicationBasePath;
optionsBuilder.UseSqlite("Filename=" + Path.Combine(path, "blog.db"));
}
}
}
将下面的代码插入到第19行。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public string Name { get; set; }
public 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 Blog Blog { get; set; }
}
namespace ConsoleApp
{
public class Program
{
public static void Main()
{
using (var db = new BloggingContext())
{
db.Blogs.Add(
new Blog
{
Name = "qin-nz",
Url = "http://cnblogs.com/qin-nz",
Posts = new[]
{
new Post{Title="post-1"},
new Post{Title="post-2"}
}.ToList()
});
var count = db.SaveChanges();
Console.WriteLine("{0} 条记录保存成功", count);
Console.WriteLine("数据库中的记录如下");
foreach (var blog in db.Blogs)
{
Console.WriteLine($"{blog.Name}({blog.Url})");
if (blog.Posts != null)
{
foreach (var post in blog.Posts)
{
Console.WriteLine($" {post.Title}");
}
}
}
}
}
}
}