Entity Framework Core
//使用VS2019依次点击:“工具”>“NuGet 包管理器”>“包管理器控制台”2 3
运行此命令安装EF: Install-Package Microsoft.EntityFrameworkCore.Sqlite
//1:首先在appsettings里面设置连接字符串2
"ConnectionStrings": {//MvcMovieContext-1是数据库的名称3
"MvcMovieContext": "Server=(localdb)\\mssqllocaldb;Database=MvcMovieContext-1;Trusted_Connection=True;MultipleActiveResultSets=true"4
}5 6
2:然后在startup里面的CongifUreServices方法里面添加7 8
services.AddDbContext<MvcMovieContext>(options =>//MvcMovieContext是数据库的名称9
options.UseSqlServer(Configuration.GetConnectionString("MvcMovieContext")));
//类名2
public class BloggingContext : DbContext3
{//类名类名4
public BloggingContext(DbContextOptions<BloggingContext> options)5
: base(options)6
{ }7
//Blog控制器,也就是类8
public DbSet<Blog> Blogs { get; set; }9
}
//EF的构造函数2
private readonly MvcMovieContext _context;3
//当前的类名EF的构造函数4
public MoviesController(MvcMovieContext context)5
{6
_context = context;7
}
public static void Main(string[] args)2
{3
var host = CreateHostBuilder(args).Build();4 5
CreateDbIfNotExists(host);6 7
host.Run();8
}9
//创建数据库10
private static void CreateDbIfNotExists(IHost host)11
{12
using (var scope = host.Services.CreateScope())13
{14
var services = scope.ServiceProvider;15 16
try17
{18
var context = services.GetRequiredService<aspcoerdeom1>();19
context.Database.EnsureCreated();20
}21
catch (Exception ex)22
{23
Console.WriteLine("创建出错!"+ex.Message);24
}25
}26
}4 1
EnsureCreated 和 EnsureDeleted //创建数据库和删除数据库2 3
创建:dbContext.Database.EnsureCreated();4
删除:dbContext.Database.EnsureDeleted();
[Table("blogs")] //定义表名2
public class Blog3
{4
public int BlogId { get; set; }5
public string Url { get; set; }6
}
//使用关系数据库时,表按约定在数据库的默认架构中创建。 例如,Microsoft SQL Server 将使用 dbo 架构(SQLite 不支持架构)。2
[Table("blogs", Schema = "blogging")]3
public class Blog4
{5
public int BlogId { get; set; }6
public string Url { get; set; }7
}
[NotMapped] //排除类型2
public class BlogMetadata3
{4
public DateTime LoadedFromDatabase { get; set; }5
}
public class Blog2
{3
[Column("blog_id")] //定义列名4
public int BlogId { get; set; }5
public string Url { get; set; }6
}
public class Blog2
{3
[MaxLength(500)]//最大值4
public int BlogId { get; set; }5
[Column(TypeName = "varchar(200)")] //定义长度6
public string Url { get; set; }7
[Column(TypeName = "decimal(5, 2)")] //定义精度为5小数为28
public decimal Rating { get; set; }9
}
public class Blog2
{3
public int BlogId { get; set; }4
[Required] //使用Required5
public string Url { get; set; }6
}
class Car2
{3
[Key] //键4
public string LicensePlate { get; set; }5
}
public class Blog2
{3
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] //可用于自增id,自身成值4
public DateTime Inserted { get; set; }5
}
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public class Person2
{3
[Timestamp]4
public string LastName { get; set; }5 6
}7
//Timestamp/rowversion 是一个属性,在每次插入或更新行时,数据库会自动为其生成新值。8
//此属性也被视为并发标记,这确保了在你查询行后,如果正在更新的行发生了更改,则会出现异常。9
//确切的详细信息取决于所使用的数据库提供程序;10
//对于 SQL Server,通常使用byte [] 属性,该属性将设置为数据库中的ROWVERSION列。
------------------查询所有数据2
using (var context = new BloggingContext())//-----using是指{}内的代码会在运行完后释放3
{4
var blogs = context.Blogs.ToList();///查询5
}6 7
------------------加载单个实体8
using (var context = new BloggingContext())9
{10
var blog = context.Blogs11
.Single(b => b.BlogId == 1);12
}13 14
------------------筛选15
using (var context = new BloggingContext())16
{17
var blogs = context.Blogs18
.Where(b => b.Url.Contains("dotnet"))19
.ToList();20
}
-------------打开解决方案跟目录:cmd2 3 4
-------------安装工具5 6
dotnet tool install --global dotnet-ef//安装命令行工具7
dotnet ef migrations add InitialCreate //生成迁移文件8 9
-------------开始迁移10 11
dotnet ef database update//迁移成功12 13
--------------如果需要拓展和更新//再次迁移14 15
dotnet ef migrations add AddBlogCreatedTimestamp16 17
--------------开始迁移18 19
dotnet ef database update//迁移成功
dotnet ef migrations remove
public static void Main(string[] args)2
{3
var host = CreateHostBuilder(args).Build();4 5
using (var scope = host.Services.CreateScope())6
{7
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();//访问8
db.Database.Migrate();//迁移9
}10 11
host.Run();12
}