代码之家  ›  专栏  ›  技术社区  ›  Eran Betzalel

为什么不能在单个服务器请求中插入带有外键的记录?

  •  7
  • Eran Betzalel  · 技术社区  · 14 年前

    我正在试着用外键做一个简单的插入,但似乎我需要使用 db.SaveChanges() 对于每个记录插入。我怎么能只用一个呢 db.savechanges()。 在这个节目结束时?

    public static void Test()
    {
        using (var entities = new DBEntities())
        {
            var sale =
                new SalesFeed
                {
                    SaleName = "Stuff...",
                };
            entities.AddToSalesFeedSet(sale);
    
            var phone =
                new CustomerPhone
                {
                    CreationDate = DateTime.UtcNow,
                    sales_feeds = sale
                };
            entities.AddToCustomerPhoneSet(phone);
    
            entities.SaveChanges();
        }
    }
    

    在运行上述代码之后,我得到了这个异常:

    System.Data.UpdateException:更新条目时出错。有关详细信息,请参见InnerException。指定的值不是有效常量类型的实例 参数名称:值。

    编辑: 更改了示例代码并添加了返回的异常。

    2 回复  |  直到 11 年前
        1
  •  15
  •   Eran Betzalel    14 年前

    表面上的使用 UNSIGNED BIGINT 导致这个问题。当我切换到 SIGNED BIGINT 一切正常。

        2
  •  2
  •   marc_s    14 年前

    我试着用“正确的方法”来做:

    alt text http://i45.tinypic.com/mcw5co.png

    然后我编写了这个小测试应用程序来扫描目录,将目录及其所有文件存储在两个表中:

    static void Main(string[] args)
    {
       string directoryName = args[0];
    
       if(!Directory.Exists(directoryName))
       {
          Console.WriteLine("ERROR: Directory '{0}' does not exist!", directoryName);
          return;
       }
    
       using (testEntities entities = new testEntities())
       {
          StoredDir dir = new StoredDir{ DirName = directoryName };
          entities.AddToStoredDirSet(dir);
    
          foreach (string filename in Directory.GetFiles(directoryName))
          {
             StoredFile stFile = new StoredFile { FileName = Path.GetFileName(filename), Directory = dir };
             entities.AddToStoredFileSet(stFile);
          }
    
          try
          {
             entities.SaveChanges();
          }
          catch(Exception exc)
          {
             string message = exc.GetType().FullName + ": " + exc.Message;
          }
       }
    }
    

    如你所见,我只有一个电话 .SaveChanges() 最后,这就像一个魅力,一切都如预期的那样。

    你的方法一定是搞砸了EF系统……