Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 db.SaveChanges() at the end of this program?

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

After running the above code I get this exception:

System.Data.UpdateException: An error occurred while updating the entries. See the InnerException for details. The specified value is not an instance of a valid constant type Parameter name: value.

EDIT: Changed example code and added returned exception.

like image 811
Eran Betzalel Avatar asked May 24 '10 08:05

Eran Betzalel


People also ask

Why can't I add a foreign key constraint?

The usual cause are generally a mismatch in the type of the column of the primary table and the foreign table. It can also be a mismatch in the Engine type of two tables i.e. MyISAM or InnoDB. Datatype both columns should have same datatype. int(11) on one table and smallint(5) on another will cause problem.

Can a single table have foreign key?

A table with a foreign key reference to itself is still limited to 253 foreign key references. Greater than 253 foreign key references are not currently available for columnstore indexes, memory-optimized tables, Stretch Database, or partitioned foreign key tables. Stretch Database is deprecated in SQL Server 2022 (16.

How can I add foreign key values to a table in SQL Server?

To create a new table containing a foreign key column that references another table, use the keyword FOREIGN KEY REFERENCES at the end of the definition of that column. Follow that with the name of the referenced table and the name of the referenced column in parentheses.

How do I fix foreign key constraint failure?

The error message itself showing there is a foreign key constraint error, which means you are deleting a parent table where the child table contains the Primary table identifier as a foreign key. To avoid this error, you need to delete child table records first and after that the parent table record.


2 Answers

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

like image 62
Eran Betzalel Avatar answered Oct 12 '22 00:10

Eran Betzalel


I tried to do this "the right way":

alt text

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.....

like image 30
marc_s Avatar answered Oct 11 '22 23:10

marc_s