<ASP.NET Core跨平台开发从入门到实战>
1.创建Asp.net Core Web Application(.NET Core)项目 NetNote,
添加引用
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Mircosoft.EntityFrameworkCore.Tools
2.设计数据库(采用EF Core Code First)
添加Models文件夹→实体→上下文
namespace NetNote.Models
{
///<summary>
///笔记
///<summary>
public class Note
{
public int Id { get; set; }
[Required]
[MaxLength(100)]
public string Title { get; set; }
[Required]
public string Content { get; set; }
public DateTime Create { get; set; }
public int TypeId { get; set; }
public NoteType Type{get;set;}
public string Password { get; set; }
public string Attachment { get; set; }
}
///<summary>
///笔记类型
///<summary>
public class NoteType
{
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
public List<Note> Notes { get; set; }
public string Password { get; set; }
public string Attachment { get; set; }
}
}
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NetNote.Models
{
public class NoteContext:DbContext
{
public NoteContext(DbContextOptions<NoteContext> options)
:base(options)
{
}
public DbSet<Note> Notes { get; set; }
public DbSet<NoteType> NoteTypes { get; set; }
}
}
3.StartUp类 在ConfigureServices方法中添加NoteContext
public void ConfigureServices(IServiceCollection services)
{
var connection = @"Data Source=DESKTOP-TCEQP8C\SQLEXPRESS;Initial Catalog=db_Student;Integrated Security=True";
services.AddDbContext<NoteContext>(options =>
options.UseSqlServer(connection));
}
4.数据库迁移,生成对应的数据库
执行
Add-Migration NoteFirst
Update-Database
5.添加一个Repository文件存放仓储文件,用于操作数据库。
添加一个 INoteRepository接口,定义增改查相关操作。
namespace NetNote.Repository
{
public interface INoteRepository
{
Task<Note> GetByIdAsync(int id);
Task<List<Note>> ListAsync();
Task AddAsync(Note note);
Task UpdateAsync(Note note);
Tuple<List<Note>, int> PageList(int pageindex, int pagesize);
}
}
namespace NetNote.Repository
{
public class NoteRepository : INoteRepository
{
private NoteContext context;
public NoteRepository(NoteContext _context)
{
context = _context;
}
public Task AddAsync(Note note)
{
context.Notes.Add(note);
return context.SaveChangesAsync();
}
public Task<Note> GetByIdAsync(int id)
{
return context.Notes.Include(type =>type.Type).FirstOrDefaultAsync(r => r.Id == id);
}
public Task<List<Note>> ListAsync()
{
return context.Notes.Include(type => type.Type).ToListAsync();
}
//后面的分页内容
public Tuple<List<Note>, int> PageList(int pageindex, int pagesize)
{
var query = context.Notes.Include(type => type.Type).AsQueryable();
var count = query.Count();
var pagecount = count % pagesize == 0 ? count / pagesize : count / pagesize + 1;
var notes = query.OrderByDescending(r => r.Create)
.Skip((pageindex - 1) * pagesize)
.Take(pagesize)
.ToList();
return new Tuple<List<Note>, int>(notes, count);
}
public Task UpdateAsync(Note note)
{
context.Entry(note).State = EntityState.Modified;
return context.SaveChangesAsync();
}
}
}
6.再次打开StartUp类,ConfigureServices方法中添加
services.AddScoped<INoteRepository , NoteRepository>();
7.添加控制器 NoteController,定义 INoteRepository变量和构造函数初始化
Add操作需要对应的实体,不建议直接使用数据库实体。
添加Viewmodels(文件夹展示对应的实体)对应都有模型验证→NoteModel类
namespace NetNote.ViewModels
{
public class NoteViewModel
{
public int Id { get; set; }
[Required]
[Display(Name ="标题")]
public string Title { get; set; }
[Display(Name ="内容")]
public string Content { get; set; }
[Display(Name ="类型")]
public int Type { get; set; }
[Display(Name ="密码")]
public string Password { get; set; }
[Display(Name ="附件")]
public IFormFile Attachment { get; set; }
}
}
public class NoteController: Controller
{
private INoteRepository _noteRepository;
public NoteController(INoteRepository noteRepository)
{
_noteRepository = noteRepository;
}
public async Task<IActionResult> Index()
{
var notes = await _noteRepository.ListAsync();
return View(notes);
}
[HttpPost]
public async Task<IActionResult> Add(NoteModel model)
{
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
await _noteRepository.AddAsync(new Note
{
Title = model.Title,
Content = model.Content,
Create = DateTime.Now
});
return RedirectToAction("Index");
}
}
8.Views文件夹→添加Note文件夹→添加Add视图和Index视图
@{
var types = ViewBag.Types as IEnumerable<SelectListItem>;
}
@model NetNote.ViewModels.NoteModel
<div class="container-fluid">
<div class="row" style="margin-top:10px;margin-bottom:10px;">
<form method="post" asp-action="Add" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="Title"></label>
<input asp-for="Title" type="text" placeholder="标题" class="form-control"/>
</div>
<div class="form-group">
<label asp-for="Content"></label>
<textarea asp-for="Content" data-provide="markdown" cols="50" class="form-control"></textarea>
</div>
@*后面的内容*@
<div class="form-group">
<label asp-for="Type"></label>
<select asp-for="Type" asp-items="types" class="from-control"></select>
</div>
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" type="password" placeholder="如需加密请输入密码" class="form-control"/>
</div>
<div class="form-group">
<label asp-for="Attachment"></label>
<inpput asp-for="Attachment" type="file" class="form-control"/>
</div>
<hr/>
<p>
<button type="submit" class="btn">保存</button>
</p>
</form>
</div>
</div>
@model List<NetNote.Models.Note>
<div class="container-fluid">
<div class="row">
<a asp-action="Add">添加Note</a>
</div>
@foreach (var item in Model)
{
<div class="row">
<h3>@item.Title</h3>
<div class="contect" id="md_@item.Id">@item.Content</div>
<hr/>
</div>
}