0

I'd like to store data in an existing table called Cars using this code:

var carlist = new Car { brand = "Nissan", model = "GTR", constructionyear = 2019, milage = 35000 };
context.Cars.Add(carlist);
context.SaveChanges();
                

When running the app the following SQL statement is generated:

> INSERT [dbo].[Cars]([brand], [model], [constructionyear], [milage])
> VALUES (@0, @1, @2, @3) SELECT [carID] FROM [dbo].[Cars] WHERE
> @@ROWCOUNT > 0 AND [carID] = scope_identity()
> -- @0: 'Nissan' (Type = AnsiString, Size = 60)
> -- @1: 'GTR' (Type = AnsiString, Size = 60)
> -- @2: '2019' (Type = Int32)
> -- @3: '35000' (Type = Int32)
> -- Executing at 16.01.2022 20:46:31 +01:00 'UB_CarPool.exe' (CLR v4.0.30319: UB_CarPool.exe): Loaded
> 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Caching\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Runtime.Caching.dll'.
> Skipped loading symbols. Module is optimized and the debugger option
> 'Just My Code' is enabled.
> -- Completed in 16 ms with result: SqlDataReader
> 
> Committed transaction at 16.01.2022 20:46:31 +01:00 Closed connection
> at 16.01.2022 20:46:31 +01:00

After closing the app, the table is still empty.

Could someone help me to understand what's going wrong?

PS: it's database first and the entity data model was made by EF Designer

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
TomU
  • 1
  • 1
  • Are you using a properly attached database, or are you attaching it using `AttachDbFilename` in the connection string? – Charlieface Jan 16 '22 at 19:55
  • I attached the database by using the EF designer, but in the connection string in my app.config there is an: attachdbfilename=|DataDirectory|\CarPoolSQL.mdf. So i guess the answer is that i'm using it. – TomU Jan 16 '22 at 20:08
  • Every time you open the connection you get a new copy of the database, and changes are lost when you close it. Instead, attach the database normally using `CREATE DATABASE... FOR ATTACH` then change your connection string to directly connect to that existing database using `Initial Catalog=YourDB` – Charlieface Jan 16 '22 at 20:11
  • I think i get the point of your post. Now i have to get the connection running. – TomU Jan 16 '22 at 20:21
  • It is working now. Thank you a lot for your help. – TomU Jan 16 '22 at 20:35
  • 1
    My problem with the proper connection was, that i could't choose my SQL Server when i tried to add a new entity data model. The list of available servers were empty. Solution: Add ADO.NET Entity Data Model -> EF Designer from database -> New Connection -> Change Data Source to "Microsoft SQL Server" -> copy your server name manually into "Server Name"-field and choose the database you want – TomU Jan 16 '22 at 20:45

0 Answers0