asp.net core连接数据库1
程序员文章站
2022-07-11 08:27:27
...
1.安装Entity Framework Core
在程序管理器控制台运行:
Install-package Microsoft.EntityFrameWorkCore.Sqlserver
运行:Install -package Microsoft.EntityFrameworkCore.Tools
2.创建一C#对象代表要查询和保存上的数据:
Blog类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace testDB.Models
{
public class Blog
{
public Blog()
{
Post = new HashSet<Post>();
}
public int BlogId { get; set; }
public string Url { get; set; }
public virtual ICollection<Post> Post { get; set; }
}
}
Post类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace testDB.Models
{
public class Post
{
public int PostId { get; set; }
public int BlogId { get; set; }
public string Content { get; set; }
public string Title { get; set; }
public virtual Blog Blog { get; set; }
}
}
创建BlogController添加数据库上下文
数据库上下文:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace testDB.Models
{
public class BloggingContext:DbContext
{
#region Constructor
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{ }
#endregion
public virtual DbSet<Blog> Blog { get; set; }
public virtual DbSet<Post> Post { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>(entity =>
{
entity.Property(e => e.Url).IsRequired();
});
modelBuilder.Entity<Post>(entity =>
{
entity.HasOne(d => d.Blog)
.WithMany(p => p.Post)
.HasForeignKey(d => d.BlogId);
});
}
}
}
Startup.cs文件:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var connection = @"Server=JOAN-PC;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0;uid=sa;pwd=abcd1234...";
services.AddDbContext<Models.BloggingContext>(options => options.UseSqlServer(connection));
}
推荐阅读
-
Asp.Net Core 学习教程1、初始.Net Core与VS Code 第一个web程序
-
asp.net 获取数据库连接字符串
-
ASP.NET数据库编程之Access连接失败
-
.Net Core 在Linux服务器下部署程序--(1). Windows 连接 Linux服务器
-
ASP.NET Core使用EF Core操作MySql数据库
-
asp.net core 系列 1 概述
-
数据库自学笔记(1)---广义笛卡尔积,投影,连接
-
asp.net连接查询SQL数据库,把结果显示在网页上
-
【.NET Core】ASP.NET Core之IdentityServer4(1):快速入门
-
gRPC in ASP.NET Core 3.0 -- Protocol Buffer(1)