[英]How to Use Enumeration within Linq Query to Update Multiple Rows in a Database
I am using ASP.NET MVC 4 and I have a View where I can see a few rows (expenses) and I have a checkbox inputs beside each row. 我正在使用ASP.NET MVC 4,我有一个View,可以看到几行(费用),每行旁边都有一个复选框输入。 There is a Boolean property called "Submitted" and a DateTime property called DateSubmitted in the model. 在模型中,有一个布尔属性“ Submitted”和一个DateTime属性DateSubmitted。
I have a method called SubmitExpenses() and I only want the rows that are 'checked' to be updated. 我有一个称为SubmitExpenses()的方法,我只希望更新“选中”的行。
The columns that would be updated are DateSubmitted and Submitted. 将要更新的列是DateSubmitted和Submitted。
Here is my model: 这是我的模型:
public class Expense
{
public Expense() { }
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ExpenseId { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
[Display(Name = "Date Submitted")]
public DateTime? DateSubmitted { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
[Display(Name = "Expense Date")]
public DateTime? ExpenseDate { get; set; }
[Display(Name = "Submitted?")]
public bool Submitted { get; set; }
[Required]
[Display(Name = "Name")]
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile UserProfile { get; set; }
}
Here is the SubmitExpenses() method: 这是SubmitExpenses()方法:
public ActionResult SubmitExpenses(List<Expense> expenses, DateTime? expenseDate = null, DateTime? expenseDate2 = null, int? userId = 0)
{
expenseDate = (DateTime)Session["FirstDate"];
expenseDate2 = (DateTime)Session["SecondDate"];
if (expenseDate == null || expenseDate2 == null)
{
expenseDate = DateTime.Now.AddMonths(-1);
expenseDate2 = DateTime.Today;
}
string currentUserId = User.Identity.Name;
var query = from e in db.Expenses
join user in db.UserProfiles on e.UserId equals user.UserId
where user.UserName == currentUserId && (e.ExpenseDate >= expenseDate && e.ExpenseDate <= expenseDate2) && e.DateSubmitted == null
orderby e.ExpenseDate descending
select e;
if (User.IsInRole("admin") && userId != 0)
{
query = from e in db.Expenses
join user in db.UserProfiles on e.UserId equals user.UserId
where user.UserId == userId && e.ExpenseDate >= expenseDate && e.ExpenseDate <= expenseDate2 && e.DateSubmitted == null
orderby e.ExpenseDate descending
select e;
}
else if (User.IsInRole("admin"))
{
query = from e in db.Expenses
join user in db.UserProfiles on e.UserId equals user.UserId
where e.ExpenseDate >= expenseDate && e.ExpenseDate <= expenseDate2 && e.DateSubmitted == null
orderby e.ExpenseDate descending
select e;
}
foreach (Expense exp in query)
{
exp.DateSubmitted = DateTime.Today;
}
try
{
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception e)
{
Console.WriteLine(e);
return RedirectToAction("Submit");
}
}
Here is the View: 这是视图:
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.DateSubmitted)
</th>
<th>
@Html.DisplayNameFor(model => model.ExpenseDate)
</th>
@if (User.IsInRole("admin"))
{
<th>
@Html.DisplayNameFor(model => model.UserProfile.UserName)
</th>
}
<th></th>
</tr>
<tr>
<td>
<b>Select All:</b>
<br />
<input type="checkbox" name="expense" value="Expense" id="selectAllCheckboxes" class="expenseCheck">
</td>
</tr>
@foreach (var item in Model)
{
<tr>
<td class="submitCheck">
@Html.DisplayFor(modelItem => item.Submitted)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateSubmitted)
</td>
<td>
@Html.DisplayFor(modelItem => item.ExpenseDate)
</td>
@if (User.IsInRole("admin"))
{
<td>
@Html.DisplayFor(modelItem => item.UserProfile.UserName)
</td>
}
</tr>
}
</table>
@Html.ActionLink("Submit Expenses", "SubmitExpenses")
@section scripts {
<script type="text/javascript">
$("#selectAllCheckboxes").click(function () {
$('.submitCheck input:checkbox').not(this).prop('checked', this.checked);
});
$('.submitCheck input:checkbox').prop('disabled', false);
</script>
}
I know how to submit all expenses that are in the date range specified (or all expenses that are showing in the view), but I'm not sure how I would update each row for only the rows that are checked. 我知道如何提交指定日期范围内的所有费用(或视图中显示的所有费用),但是我不确定如何只为已检查的行更新每一行。
Thank you. 谢谢。
First, as an aside, you can use query composition instead of repeating your query each time: 首先,顺便说一句,您可以使用查询组合而不是每次都重复查询:
var query = from e in db.Expenses
join user in db.UserProfiles on e.UserId equals user.UserId
where e.ExpenseDate >= expenseDate && e.ExpenseDate <= expenseDate2 && e.DateSubmitted == null
orderby e.ExpenseDate descending
select new { e, user };
if (User.IsInRole("admin") && userId != 0)
{
query = query.Where(x => x.user.UserId == userId);
}
else if (!User.IsInRole("admin"))
{
query = query.Where(x => x.user.UserName == currentUserId);
}
Now for the question: If I understand you correctly you want to filter out the Expenses from the database that were marked as Submitted
in the view. 现在开始提问:如果我对您的理解正确,那么您想从数据库中过滤掉视图中标记为“已Submitted
的费用。 These filtered expenses should be updated. 这些过滤的费用应更新。 A way to do that is by joining the database expenses with the ones from the view: 一种方法是将数据库费用与视图中的费用合并在一起:
var joined = from dbExpense in query.Select(x => x.e).AsEnumerable()
join localExpense in expenses on dbExpense.ExpenseId equals localExpense.ExpenseId
where localExpense.Submitted
select dbExpense;
foreach (Expense exp in joined)
{
exp.DateSubmitted = DateTime.Today;
}
By using AsEnumerable
on the database query, you can join it with a local sequence ( expenses
) as LINQ to objects. 通过在数据库查询上使用AsEnumerable
,您可以将其与本地序列( expenses
)作为LINQ连接到对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.