【问题标题】:How do I switch out one list's objects with another list's object如何用另一个列表的对象切换一个列表的对象
【发布时间】:2020-05-13 23:02:56
【问题描述】:

我有这个包含项目的数据库,每个项目都有一个附加的数据点列表。 我想更新列表,这是我的方法

var currentDataPoints = db.CurrentPriceTableModels.Include(x => x.The30DayPoints).FirstOrDefault(x => x.ItemId == currentDatabaseItem.ItemId).The30DayPoints;
foreach (var currentDataPoint in currentDataPoints)
{
    currentDataPoint.Ts = ...

    db.Update(currentDataPoint);
    db.SaveChanges();
}

我面临的问题是我想从本质上为这个对象集合中的每个对象切换出每个 currentDataPoint var dataPointApi = JsonConvert.DeserializeObject<The30DataPointsModel[]>(itemUrl).ToList();

我不能做currentDataPoints = dataPointApi; 因为我不能向数据库中添加一个列表,它会抛出一个异常。因此,我需要像上面的 foreach 循环一样逐一更新每个项目。 关于如何访问dataPointApi 中的每个对象属性并将值分配给currentDataPointproperties 的任何想法?

【问题讨论】:

  • 您想将匹配的 currentDataPoints 对象替换为所有等价的 dataPointApi 对象吗?并且不匹配的保留在 currentDataPoints 列表中吗?或者你只想用 datPointApi 替换整个 currentDataPoints 而不管匹配。

标签: c# .net entity-framework entity-framework-core


【解决方案1】:

试试这段代码:

var currentDataPoints = db.CurrentPriceTableModels.Include(x => x.The30DayPoints).FirstOrDefault(x => x.ItemId == currentDatabaseItem.ItemId).The30DayPoints;

currentDataPoints.ForEach(d => d.Ts = ...); // assign here the value you need

db.UpdateRange(currentDataPoint);
db.SaveChanges(); // only once SaveChanges call, which will improve the performace

【讨论】:

    猜你喜欢
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2015-09-03
    • 2014-07-12
    • 2023-03-18
    • 2014-02-17
    相关资源
    最近更新 更多