Hiển thị data
Sử dụng Lambda Expressions:
- FirstOrDefault()
- Where()
- ToList()
Sử dụng thêm các cú pháp của SQL như select, where, from, in, order by..)
Quay trở lại project tạo một CategoriesController
public class CategoriesController : Controller
{
private BloggingContext _bloggingContext;
public CategoriesController(BloggingContext bloggingContext)
{
_bloggingContext = bloggingContext;
}
public IActionResult Index()
{
var model = _bloggingContext.Categories.ToList();
return View(model);
}
}
Tạo view
Tạo dòng:
- Tạo một object
- Thêm data cho object mới tạo
- Sử dụng method add của DbContext
- Sử dụng SaveChanges
Thêm Action Create trong CategoriesController
===
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind()]Categories categories)
{
try
{
if (ModelState.IsValid)
{
_bloggingContext.Add(categories);
await _bloggingContext.SaveChangesAsync();
return RedirectToAction("Index");
}
}
catch (DbUpdateException)
{
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists " +
"see your system administrator.");
}
return View(categories);
}
===
Thuộc tính ValidateAntiForgeryToken giúp ngăn chặn các cuộc tấn công giả mạo Cross-Site (CSRF), mã này sẽ được tự động thêm vào khi sử dụng mẫu.
View của page Create
===
<form asp-action="Create" method="post">
<div class="form-horizontal">
<h4>Categories</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="ParentId" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="ParentId" class="form-control" />
<span asp-validation-for="ParentId" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="NameUnsign" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="NameUnsign" class="form-control" />
<span asp-validation-for="NameUnsign" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Active" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Active" class="form-control" />
<span asp-validation-for="Active" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Icon" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Icon" class="form-control" />
<span asp-validation-for="Icon" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>
===
Edit record
===
[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditPost(int? id)
{
if (id == null)
{
return NotFound();
}
var category = await _bloggingContext.Categories.SingleOrDefaultAsync(x => x.Id == id);
if (await TryUpdateModelAsync<Categories>(
category,
"",
x => x.Name, x => x.NameUnsign, x => x.Active))
{
try
{
await _bloggingContext.SaveChangesAsync();
return RedirectToAction("Index");
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.)
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists, " +
"see your system administrator.");
}
}
return View(category);
}
=== Phương thức này đòi hỏi phải thêm cơ sở dữ liệu đọc và có thể dẫn đến xử lý mã phức tạp hơn
Phương pháp thay thế (tuy nhiên đây chỉ là một cách tiếp nhận tùy chọn)
===
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name,ParentId,NameUnsign,Active,Icon")]Categories category)
{
if (id != category.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_bloggingContext.Update(category);
await _bloggingContext.SaveChangesAsync();
return RedirectToAction("Index");
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.)
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists, " +
"see your system administrator.");
}
}
return View(category);
}
===
Delete record
===
public async Task<IActionResult> Delete(int? id, bool? saveChangesError = false)
{
if (id == null)
{
return NotFound();
}
var category = await _bloggingContext.Categories
.AsNoTracking()
.SingleOrDefaultAsync(x => x.Id == id);
if (category == null)
{
return NotFound();
}
if (saveChangesError.GetValueOrDefault())
{
ViewData["ErrorMessage"] =
"Delete failed. Try again, and if the problem persists " +
"see your system administrator.";
}
return View(category);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var category = await _bloggingContext.Categories
.AsNoTracking()
.SingleOrDefaultAsync(x => x.Id == id);
if (category == null)
{
return RedirectToAction("Index");
}
try
{
_bloggingContext.Categories.Remove(category);
await _bloggingContext.SaveChangesAsync();
return RedirectToAction("Index");
}
catch (DbUpdateException)
{
//Log the error (uncomment ex variable name and write a log.)
return RedirectToAction("Delete", new { id = id, saveChangesError = true }); ;
}
}
===
Nếu cải thiện hiệu suất trong một ứng dụng lớn cần được ưu tiên thì nên tránh các truy vấn SQL không cần thiết
===
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
try
{
Categories category = new Categories() { Id = id };
_bloggingContext.Entry(category).State = EntityState.Deleted;
await _bloggingContext.SaveChangesAsync();
return RedirectToAction("Index");
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.)
return RedirectToAction("Delete", new { id = id, saveChangesError = true });
}
}
===
Nguồn :
https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud
http://www.c-sharpcorner.com/UploadFile/ff2f08/entity-framework-and-asnotracking/
http://www.c-sharpcorner.com/UploadFile/ff2f08/logging-and-intercepting-database-operations-with-entity-fra/
Thứ Hai, 17 tháng 7, 2017
.Net Core
Đăng ký:
Đăng Nhận xét (Atom)

Không có nhận xét nào:
Đăng nhận xét