I'm trying to insert some data in my database using Entity Framework model, but for some unknown reasons to me, it does nothing.
Am I missing something here?
using (var context = new DatabaseEntities()) { var t = new test { ID = Guid.NewGuid(), name = "blah", }; context.AddTotest(t); context.SaveChanges(); }
Insert DataUse the DbSet. Add method to add a new entity to a context (instance of DbContext ), which will insert a new record in the database when you call the SaveChanges() method. In the above example, context. Students.
In the Solution Explorer, right-click on the project and choose "Add New Item". It will open an "Add New Item" dialog box. Choose the "ADO.NET Entity Data Model" and change the default name from "Model. edmx" to "Employee.
You can add multiple records or multiple objects using the AddRange method of DbSet as shown in the following code. The code creates a list of department objects and inserts two new departments to the list. We add the list to the context using the AddRange method.
It should be:
context.TableName.AddObject(TableEntityInstance);
Where:
TableName
: the name of the table in the database.TableEntityInstance
: an instance of the table entity class.If your table is Orders
, then:
Order order = new Order(); context.Orders.AddObject(order);
For example:
var id = Guid.NewGuid(); // insert using (var db = new EfContext("name=EfSample")) { var customers = db.Set<Customer>(); customers.Add( new Customer { CustomerId = id, Name = "John Doe" } ); db.SaveChanges(); }
Here is a live example:
public void UpdatePlayerScreen(byte[] imageBytes, string installationKey) { var player = (from p in this.ObjectContext.Players where p.InstallationKey == installationKey select p).FirstOrDefault(); var current = (from d in this.ObjectContext.Screenshots where d.PlayerID == player.ID select d).FirstOrDefault(); if (current != null) { current.Screen = imageBytes; current.Refreshed = DateTime.Now; this.ObjectContext.SaveChanges(); } else { Screenshot screenshot = new Screenshot(); screenshot.ID = Guid.NewGuid(); screenshot.Interval = 1000; screenshot.IsTurnedOn = true; screenshot.PlayerID = player.ID; screenshot.Refreshed = DateTime.Now; screenshot.Screen = imageBytes; this.ObjectContext.Screenshots.AddObject(screenshot); this.ObjectContext.SaveChanges(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With