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

后端 未结 3 946
走了就别回头了
走了就别回头了 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 20:54

    Apperantly using UNSIGNED BIGINT causes this problem. When I switched to SIGNED BIGINT everything worked as it supposed to.

    0 讨论(0)
  • 2020-12-31 20:56

    it might be related with the implementation of AddToSalesFeedSet etc.. there is chance that you are doing commit inside ?

    any way, my point is that i encountered very close problem, was tring to add relation to new entity with existed entity that been queried earlier - that has unsigned key and got the same exception;

    the solution was to call Db.collection.Attach(previouslyQueriedEntityInstance);

    0 讨论(0)
  • 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.....

    0 讨论(0)
提交回复
热议问题