Use the Entity Framework model to insert data.

.net c# entity-framework

Question

I'm attempting to use the Entity Framework model to enter some data into my database, but for some reason that escapes me, nothing happens.

Am I overlooking something here?

using (var context = new DatabaseEntities())
{
    var t = new test
    {
        ID = Guid.NewGuid(),
        name = "blah",
    };
    context.AddTotest(t);
    context.SaveChanges();
}
1
87
5/15/2014 11:36:56 AM

Accepted Answer

It ought to be:

context.TableName.AddObject(TableEntityInstance);

Where:

  1. TableName : the title of the database table.
  2. TableEntityInstance : a representative of the class of table entities.

Should your table beOrders , then:

Order order = new Order();
context.Orders.AddObject(order);

For instance:

 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 an actual instance:

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();
  }
}
111
8/10/2015 6:33:24 PM

Popular Answer

var context = new DatabaseEntities();

var t = new test //Make sure you have a table called test in DB
{
    ID = Guid.NewGuid(),
    name = "blah",
};

context.test.Add(t);
context.SaveChanges();

Should be done



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow