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

bmp9r5qi  于 2023-01-22  发布在  .NET
关注(0)|答案(3)|浏览(135)

我试图使用实体框架模型在数据库中插入一些数据,但是由于一些未知的原因,它什么也没做。
我错过什么了吗?

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

kr98yfug1#

它应该是:

context.TableName.Add(TableEntityInstance);

实体框架6之前的版本为:

context.TableName.AddObject(TableEntityInstance);

其中:

  1. TableName:数据库中表的名称。
  2. TableEntityInstance:表实体类的示例。
    如果您的表是Orders,则:
Order order = new Order();
context.Orders.Add(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.Add(screenshot);
    this.ObjectContext.SaveChanges();
  }
}
oyjwcjzk

oyjwcjzk2#

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

应该这样做

z9ju0rcb

z9ju0rcb3#

[HttpPost] //在按钮单击事件上编写逻辑时使用

public ActionResult DemoInsert(EmployeeModel emp)
{
    Employee emptbl = new Employee();    // make object of table
    emptbl.EmpName = emp.EmpName;
    emptbl.EmpAddress = emp.EmpAddress;  // add if any field you want insert
    dbc.Employees.Add(emptbl);           // pass the table object 
    dbc.SaveChanges();

    return View();
}

相关问题