1

I want to add a new book to my database, but it doesn't work.

class Program
    {
        static void Main(string[] args)
        {
            Knigi_DataEntities entities = new Knigi_DataEntities();
                Books newBook = new Books();
                newBook.Name = "C# 4 How-to";
                newBook.Published = 2010;
                newBook.Book_ID = 4;
                entities.AddToBooks(newBook);
                entities.SaveChanges();

            Knigi_DataEntities ent = new Knigi_DataEntities(); 
                  foreach (var book in ent.Books)
                {
                    Console.WriteLine("{0}, {1} {2}  ",
                    book.Book_ID, book.Name, book.Published);
                }
              }
            }

but when I close //entities.SaveChanges();, the console displays objects that are already in my database. Therefore problems are caused by entities.SaveChanges();
Please tell me, how to add new objects?

3 Answers3

2

you can try this

 entities.Books.AddObject(newBook);
 entities.SaveChanges();
COLD TOLD
  • 13,513
  • 3
  • 35
  • 52
0

Are you sure that the Id isn t a primary key and therefor it want to auto generate one and you don t have to input it?

Maximc
  • 1,722
  • 1
  • 23
  • 37
0

One problem here could be that you have a Primary Key of type int that is not set to AutoIncrement in your database. The problem that would occur when creating a new Books is that a default value for an int is 0 and that this ID already exists in your database.

A solution would be to set it to AutoIncrement in your database or to check for the highest ID, add 1, assign it to your Books object and insert it.

In this case I would go with an AutoIncrement because it is the easiest and you don't have to account for concurrency.

Silvermind
  • 5,791
  • 2
  • 24
  • 44
  • If we are talking about MSSQL than you could open the table designer, select your primary key column and set the increment to true in the properties window. – Silvermind Oct 22 '12 at 00:16