C# 是否可以使用await\u db.SaveChangesAsync一次添加一条记录
我正在开发一个ASP.NETRazor页面应用程序。当用户输入年份时,事件处理程序将在一个页面上确定该年第一个星期日的日期,并在文本框中显示该日期。On-Post处理程序将日期保存到数据库中,然后在第一个星期日的基础上增加七天,以确定下一个星期日的日期。当OnPost试图保存下周日日期时,程序崩溃。是否可以使用我的代码一次保存多条记录?有没有更好的方法来完成我想做的事情C# 是否可以使用await\u db.SaveChangesAsync一次添加一条记录,c#,asp.net-core,C#,Asp.net Core,我正在开发一个ASP.NETRazor页面应用程序。当用户输入年份时,事件处理程序将在一个页面上确定该年第一个星期日的日期,并在文本框中显示该日期。On-Post处理程序将日期保存到数据库中,然后在第一个星期日的基础上增加七天,以确定下一个星期日的日期。当OnPost试图保存下周日日期时,程序崩溃。是否可以使用我的代码一次保存多条记录?有没有更好的方法来完成我想做的事情 //*****cshtml.cs***** using System; using System.Collections.Ge
//*****cshtml.cs*****
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection.Metadata;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.CodeAnalysis;
using PublicTalkSchedule.Data;
using PublicTalkSchedule.Models;
using Document = System.Reflection.Metadata.Document;
namespace PublicTalkSchedule.Pages.TalksIncoming
{
public class CreateModel : PageModel
{
private readonly ApplicationDbContext _db;
public CreateModel(ApplicationDbContext db)
{
_db = db;
}
// ***** success message - displays message from create, edit or delete page *****
[TempData]
public string Message { get; set; }
public string lblMessage { get; set; }
public DateTime currentDate { get; set; }
public int weekDay { get; set; }
[Required(ErrorMessage = "The Year field is required... ")]
public string txtYear { get; set; }
[Required(ErrorMessage = "The Sunday Date field is required... ")]
public string txtSunday { get; set; }
[BindProperty]
public ScheduleIn scheduleIn { get; set; }
// OnGet
public IActionResult OnGet(DateTime sunDate, string newYear)
{
//determine if sunDate is a valid Sunday date for the selected year. if valid, run code. if blank
//(MinValue equals 01/01/0001 and indicates a blank textbox), skip code. the initialize schedule page appears
if (sunDate != DateTime.MinValue)
{
txtYear = newYear;
var strSunday = sunDate.ToString("MM/dd/yyyy");
txtSunday = strSunday;
}
txtYear = newYear;
return Page();
}
// OnPost
public async Task<IActionResult> OnPostAsync()
{
var newYear = Request.Form["txtYear"]; //get the first Sunday from the page
DateTime yearEndMarker = Convert.ToDateTime("12/25/" + newYear);
var newSunday = Request.Form["txtSunday"]; //get the first Sunday from the page
DateTime currentSunday = Convert.ToDateTime(newSunday); //convert String to DateTime
scheduleIn.DOT = currentSunday;
do
{
_db.ScheduleIn.Add(scheduleIn);
await _db.SaveChangesAsync();
currentSunday = currentSunday.AddDays(7);
scheduleIn.DOT = currentSunday;
} while (currentSunday.Date <= yearEndMarker.Date);
return RedirectToPage("Index"); //return to Index page
}
//On Post - Initialize Year
public async Task<IActionResult> OnPostInitializeYear()
{
var newYear = Request.Form["txtYear"]; //get the selected year
//add newYear to jan. 1, then convert to datetime.
currentDate = Convert.ToDateTime("01/01/" + newYear);
weekDay = Convert.ToInt32(currentDate.DayOfWeek);
//determine he first Sunday in the year. increase sunDate by 1 until weekDay equals 0 )
do
{
currentDate = currentDate.AddDays(1);
weekDay = Convert.ToInt32(currentDate.DayOfWeek);
}
while (weekDay != 0);
return RedirectToPage("Create", new { sunDate = currentDate, newYear = newYear });
}
}
}
//*****cshtml
@page
@model PublicTalkSchedule.Pages.TalksIncoming.CreateModel
@{
ViewData["Title"] = "Create";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<!-- *************** code used to display success message *************** -->
@if (Model.Message != null)
{
<div class="alert alert-info alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aira-label="close">
<span aria-hidden="true">×</span>
</button>
@Model.Message
</div>
}
<!-- ****************************** Create (initilize) Incoming New Year Schedule Banner ****************************** -->
<br />
<h4 class="text-info"> Initilize New Calendar Year for Incomming Talk Schedule</h4>
<br />
<form method="post">
<div class="border backgroundwhite">
<!-- setup border, texbox (for new calendar year) and submit button-->
<div style="height:110px;" class="container border border-secondary">
<div class="row">
<div class="col-12">
<div class="row" style="padding-top:10px">
<div class="col-1"></div>
<!-- textbox NewYear-->
<div class="col-4 text-right">
<h4 id="lblYear" class="text-info pl-1 pt-1 pb-1">Enter New Year:</h4>
</div>
<div class="col-2">
<input type="text" asp-for="txtYear" runat="server" id="txtYear"
class="text-black pl-1 pt-1 pb-1" style="width:90px; text-align:center" />
</div>
<span asp-validation-for="txtYear" class="text-danger"></span>
<div class="col-1"></div>
<div class="col-2 text-right">
<!-- submit button -->
<button type="submit" asp-page-handler="InitializeYear" runat="server"
class="form-control btn btn-primary">
Submit
</button>
</div>
</div>
</div>
<br />
<!-- *************** if tstYear is null, then hide txtSunday and txtLabel ***************-->
<!-- display first sunday date for new calendar year with confirm button -->
@if (!String.IsNullOrWhiteSpace(Model.txtYear))
{
<div class="col-12">
<div class="row" style="padding-top:5px">
<div class="col-2"></div>
<!--txtSunay-->
<div class="col-11 offset-2" style="padding-bottom:10px" text-align:center>
<input type="text" asp-for="txtSunday" runat="server" id="txtSunday"
class="text-black pl-1 pt-1 pb-1" style="width:100px" ; text-align:center />
<h10 id="lblSunday" class="text-info pl-1 pt-5 pb-1">is the FIRST Sunday the year. If this is correct, click Create</h10>
</div>
<!--lblSunday-->
@*<div class="col-8">
<h10 id="lblSunday" class="text-info pl-1 pt-5 pb-1">is the FIRST Sunday the year. If this is correct, click Continue</h10>
</div>*@
</div>
</div>
}
<!-- ************************* LAST LINE OF HIDEN IV SECTION ***************-->
</div>
</div>
<br />
<!-- add buttons-->
<div class="form-group row">
<div class="col-5 offset-3">
<partial name="_CreateAndBackToListButton" />
</div>
</div>
</div>
</form>
@section Scripts{
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
/****cshtml.cs*****
使用制度;
使用System.Collections.Generic;
使用System.ComponentModel.DataAnnotations;
使用System.Linq;
使用System.Reflection.Metadata;
使用System.Threading.Tasks;
使用Microsoft.AspNetCore.Mvc;
使用Microsoft.AspNetCore.Mvc.RazorPages;
使用Microsoft.CodeAnalysis;
使用PublicTalkSchedule.数据;
使用PublicTalkSchedule.Models;
使用Document=System.Reflection.Metadata.Document;
命名空间PublicTalkSchedule.Pages.TalksIncoming
{
公共类CreateModel:PageModel
{
私有只读应用程序dbContext_db;
公共CreateModel(ApplicationDbContext数据库)
{
_db=db;
}
//******成功消息-显示“创建、编辑或删除”页面中的消息*****
[临时数据]
公共字符串消息{get;set;}
公共字符串lblMessage{get;set;}
公共日期时间currentDate{get;set;}
公共int工作日{get;set;}
[必需(ErrorMessage=“年份字段是必需的…”)]
公共字符串txtYear{get;set;}
[必需(ErrorMessage=“星期日日期字段是必需的…”)]
公共字符串txtstunday{get;set;}
[BindProperty]
public ScheduleIn ScheduleIn{get;set;}
//昂吉
公共IActionResult OnGet(日期时间圣代,字符串新年)
{
//确定sunDate是否为所选年份的有效星期日日期。如果有效,请运行代码。如果为空
//(MinValue等于01/01/0001,表示一个空白文本框),跳过代码。此时会显示初始化计划页面
if(圣代!=DateTime.MinValue)
{
txtYear=新年;
变量strSunday=sunDate.ToString(“MM/dd/yyyy”);
txtsday=strSunday;
}
txtYear=新年;
返回页();
}
//在岗
公共异步任务OnPostAsync()
{
var newYear=Request.Form[“txtYear”];//从页面获取第一个星期日
DateTime yearEndMarker=Convert.ToDateTime(“12/25/”+newYear);
var newSunday=Request.Form[“txtstanday”];//从页面获取第一个星期日
DateTime currentSunday=Convert.ToDateTime(newSunday);//将字符串转换为日期时间
scheduleIn.DOT=当前星期日;
做
{
_db.ScheduleIn.Add(ScheduleIn);
等待_db.SaveChangesAsync();
currentSunday=currentSunday.AddDays(7);
scheduleIn.DOT=当前星期日;
}while(当前星期日日期)
@如果(Model.Message!=null)
{
@如果(!String.IsNullOrWhiteSpace(Model.txtYear))
{
@*
如果您想坚持使用纯实体框架,那么您无法实现这一点。因为每个实体框架调用都将转换为sql语句。因此,它将是多个调用
根据您的使用场景,您可以:
创建一个存储过程并在其中添加您的计划。它将在
一次调用,比实体框架更有效。您只需调用它
从实体框架
原始SQL查询。与sp类似,但您在c#中创建SQL语句。有SQL注入的危险,但只要您
正确地参数化sql,没有问题
也就是说,如果你的页面足够快,你可能就不必费心去坚持EF了。简单地说,代码没有意识到循环中的每个新日期都应该被视为要插入数据库的新记录。Do While语句的前三行解决了这个问题
// OnPost
public async Task<IActionResult> OnPostAsync()
{
var newYear = Request.Form["txtYear"];
DateTime yearEndMarker = Convert.ToDateTime("12/31/"
+ newYear);
var newSunday = Request.Form["txtSunday"];
DateTime currentSunday =
Convert.ToDateTime(newSunday);
do
{
//the next three lines makes each iteration
//appear as a new record to be saved
scheduleIn = new ScheduleIn()
{
DOT = currentSunday
};
_db.ScheduleIn.Add(scheduleIn);
await _db.SaveChangesAsync();
currentSunday = currentSunday.AddDays(7);
} while (currentSunday.Date <=
yearEndMarker.Date);
Message = "The year " + newYear + " has been
successfully initialized";
return RedirectToPage("Index");
}
//OnPost
公共异步任务OnPostAsync()
{
var newYear=Request.Form[“txtYear”];
DateTime yearEndMarker=Convert.ToDateTime(“12/31/”
+新年),;
var newSunday=Request.Form[“txtstunday”];
日期时间currentSunday=
转换.ToDateTime(新闻星期日);
做
{
//接下来的三行进行每次迭代
//显示为要保存的新记录
scheduleIn=新scheduleIn()
{
点=当前星期日
};
_db.ScheduleIn.Add(ScheduleIn);
等待_db.SaveChangesAsync();
currentSunday=currentSunday.AddDays(7);
}while(currentSunday.Date)感谢您的回复。您能提供一个我可以使用的SQL查询示例吗?我假设查询可以放在OnPost中,对吗?