一尘不染

使用实体框架模型插入数据

c#

我正在尝试使用Entity Framework模型在数据库中插入一些数据,但是由于某些未知的原因,它什么也不做。

我在这里想念什么吗?

using (var context = new DatabaseEntities())
{
    var t = new test
    {
        ID = Guid.NewGuid(),
        name = "blah",
    };
    context.AddTotest(t);
    context.SaveChanges();
}

阅读 227

收藏
2020-05-19

共1个答案

一尘不染

它应该是:

context.TableName.AddObject(TableEntityInstance);

哪里:

  1. TableName:数据库中表的名称。
  2. TableEntityInstance:表实体类的实例。

如果您的表是Orders,则:

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

例如:

 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();
 }

这是一个实时示例:

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();
  }
}
2020-05-19