[英]How do i retrieve column data from this list
I only have the id for the specific line of data which is saved in item. 我只有保存在item中的特定数据行的id。 I am trying to retrieve extra data to use in an insert statement to keep a log of who deletes on the system.
我正在尝试检索用于插入语句的额外数据,以记录谁在系统上进行了删除。
public static void DeleteFromClass(this Entities context, List<long> ids, string deletedBy)
{
if (ids.Count == 0) return;
foreach (var item in ids)
{
var result = (from details in context.Class
where details.ID == item
select new
{
id = item,
studNumber = details.studNumber,
name = details.name,
lastName = details.lastName,
}).ToList();
var InsertQuery = "INSERT INTO DeletedStudents (studNumber, name, lastName, DeletedBy, DeletedOn, stage) " +
"VALUES (" + result.Where(e => e.id == item).Select(e => e.studNumber) + "," + result.Where(e => e.id == item).Select(e => e.name) + "," + result.Where(e => e.id == item).Select(e => e.lastName) + "," + deletedBy + "," + DateTime.Now + ", 1) ";
}
}
This code doesn't do what you think. 这段代码与您的想法不符。
result.Where(e => e.id == item).Select(e => e.studNumber)
^ That code returns an object representing zero or more records. ^该代码返回一个表示零个或多个记录的对象。 You probably did not mean to concatenate it as a string.
您可能并不打算将其串联为字符串。
If you want to get a single string from a single record, you could do something like this: 如果要从单个记录中获取单个字符串,则可以执行以下操作:
result.Single(e => e.id == item).studNumber
If you think there may be more than one record returned, perhaps you just want to use the first one: 如果您认为可能返回了多个记录,那么您可能只想使用第一个记录:
result.First(e => e.id == item).studNumber
And if you're not sure there is a record, you could do something like this: 如果不确定是否有记录,可以执行以下操作:
result.FirstOrDefault(e => e.id == item)?.studNumber ?? ""
Or if you want an insert statement for each record: 或者,如果您想为每个记录插入一条语句:
string[] sql = result.Select( e => "INSERT blah blah VALUES (" + e.studNumber + ").ToArray();
That all being said, you probably should not concatenate strings to form SQL statements . 综上所述,您可能不应该将字符串连接起来以形成SQL语句 。 You should use a stored procedure with strongly-typed arguments.
您应该使用带有强类型参数的存储过程。
Or better yet, don't mix and match EF and SQL. 或者更好的是,不要混合和匹配EF和SQL。 Use the EF to do the inserts instead.
使用EF代替插入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.