我有这个C#和linq to database来从数据库中获取所有数据行
var getOldAttachment = _context.ca_Attachments.Where(x => x.CaseId == getCase[0].Id && x.isDeleted == false).ToList();
我想使用foreach通过更新新数据列将确切的数据行重新插入到数据库中,简单来说就是复制相同的数据行但具有不同的值。数据行包含 Id,creator,attachmentid,lastupdateon 。值为: 1,tester,12345,2015-11-16 11:49:50.810 我只想将编辑器的值更改为当前使用哪个调用编辑器。我想把什么放在????部?
if (getOldAttachment != null && getOldAttachment.Count > 0)
{
//foreach (??????)
//{
// data.ca_Attachments.Add(new ca_Attachment
// {
// AttachmentId = getOldAttachment.attachmentId,
// creator = editor,
// LastUpdatedOn = _startTime,
// });
//}
}
答案 0 :(得分:2)
注意:您不需要在null
之后检查ToList()
。它永远不会为空。您也不需要检查Count > 0
,因为我们要对其进行迭代(如果没有任何项目,它将无法执行)。
您可以简单地写一下:
var oldAttachments = _context.ca_Attachments
.Where(x => x.CaseId == getCase[0].Id && !x.isDeleted)
.ToList();
foreach (var oldAttachment in oldAttachments)
{
data.ca_Attachments.Add(new ca_Attachment
{
AttachmentId = oldAttachment.attachmentId,
creator = editor,
LastUpdatedOn = _startTime,
});
}
答案 1 :(得分:1)
以下是使用ForEach
的一个选项:
getOldAttachment.ForEach(att => {
_context.ca_Attachments.Add(new ca_Attachment
{
AttachmentId = att.attachmentId,
creator = editor,
LastUpdatedOn = _startTime,
});
});
这使用_context
添加新附件而不是data
- 不确定data
是什么......
答案 2 :(得分:0)
if (getOldAttachment != null && getOldAttachment.Count > 0)
{
for(var i = 0; i < getOldAttachment.Count; i++)
{
//this is how to populate the data from list
//sample only
ca_Attachment.AttachmentId = getOldAttachment[i].AttachmentId;
//do the insert code
}
}