在实体中插入数据2次

时间:2016-02-17 16:38:19

标签: c# entity-framework linq linq-to-entities

对不起,它一定是一个新手问题,但我没有找到任何解决方案,现在仍然存在2个小时的问题。 我有以下代码:

foreach (Stock s in queryStocks)
{
  int checkTimeCount;

  checkTimeCount = (from ph in entity.StockPriceHistories
                    where ph.StockStockId == s.StockId
                    orderby ph.StockPriceHistoryDate descending
                    select ph.StockPriceHistoryDate).Count();
  if (checkTimeCount != 0)
  {
    var checkTimeStock = (from ph in entity.StockPriceHistories
                          where ph.StockStockId == s.StockId
                          orderby ph.StockPriceHistoryDate descending
                          select ph.StockPriceHistoryDate).First();

    string checkTimeStringStock = checkTimeStock.ToShortDateString();

    if (dateNow != checkTimeStringStock)
    {
      StockPriceHistory ph = new StockPriceHistory();
      ph.StockPriceHistoryDate = DateTime.Now;
      ph.StockStockId = s.StockId;
      ph.Value = s.Value;
      entity.StockPriceHistories.Add(ph);
    }
  }
  else
  {
    StockPriceHistory ph = new StockPriceHistory();
    ph.StockPriceHistoryDate = DateTime.Now;
    ph.StockStockId = s.StockId;
    ph.Value = s.Value;
    entity.StockPriceHistories.Add(ph);
  }

}


                // Submit the changes to the database.
                #region SaveChangesDB
                try
                {
                    entity.SaveChanges();
                }
                catch
                {
                // Provide for exceptions.
                }
                #endregion

这一次每次插入ph(StockPriceHistory模型)两次。我只想插入一个...我真的不明白为什么。让我疯了!

提前致谢并再次抱歉这个noob问题和我的英语不好,

阿德里安

评论1后

编辑:  queryStock debug screen

我在这里看不到重复,或者我错过了什么?首先是股票与股票1和第二是股票与stockid 2。 这是queryStocks,如果它可以帮助: var queryStocks = from s in entity.Stocks select s; //获取DB中的所有股票

感谢您的快速回答

编辑2: 插入结果&日期格式

Insert

日期格式:“18/02/2016”每个(dateNow& checkTimeStringStock)

编辑3:

count

这个查询如何从EDIT 2屏幕截图中的表中返回2结果?

编辑4:我的不好,数量还可以,因为我是在一个foreach

1 个答案:

答案 0 :(得分:0)

那是菜鸟。 这个foreach是在另一个foreach(Portofolio ...),我有2 portofolio所以这个结果是正常的。

foreach (Portofolio ord in query)
    {

      ...

        foreach (Stock x in queryStockValue)
        {

现在没问题。