Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert data using Entity Framework model

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(); } 
like image 295
Rocshy Avatar asked Jan 12 '12 12:01

Rocshy


People also ask

How do I insert a record into Entity Framework?

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.

How do I add data to EDMX?

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.

How do I insert multiple rows in Entity Framework?

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.


1 Answers

It should be:

context.TableName.AddObject(TableEntityInstance); 

Where:

  1. TableName: the name of the table in the database.
  2. 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();   } } 
like image 170
Friend Avatar answered Sep 26 '22 02:09

Friend