Why can't I insert record with foreign key in a single server request?

后端 未结 3 972
走了就别回头了
走了就别回头了 2020-12-31 20:46

I\'m tryring to do a simple insert with foreign key, but it seems that I need to use db.SaveChanges() for every record insert. How can I manage to use only one

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-31 21:08

    I tried to do this "the right way":

    And then I wrote this little test app to scan a directory, store the directory and all its files in two tables:

    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;
          }
       }
    }
    

    As you can see, I only have a single call to .SaveChanges() at the very end - this works like a charm, everything's as expected.

    Something about your approach must be screwing up the EF system.....

提交回复
热议问题