使用Entity Framework模型插入数据

时间:2012-01-12 12:57:07

标签: c# .net entity-framework

我正在尝试使用Entity Framework模型在我的数据库中插入一些数据,但由于某些未知原因,我没有做任何事情。

我在这里错过了什么吗?

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

4 个答案:

答案 0 :(得分:94)

应该是:

context.TableName.AddObject(TableEntityInstance);

其中:

  1. TableName:数据库中表的名称。
  2. TableEntityInstance:表实体类的实例。
  3. 如果您的表格为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();
      }
    }
    

答案 1 :(得分:36)

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

应该这样做

答案 2 :(得分:6)

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

答案 3 :(得分:3)

我正在使用EF6,我发现了一些奇怪的东西,

假设Customer具有带参数的构造函数,

如果我使用new Customer(id, "name"),并执行

 using (var db = new EfContext("name=EfSample"))
 {
    db.Customers.Add( new Customer(id, "name") );
    db.SaveChanges();
 }

它没有错误地运行,但是当我查看DataBase时,我发现事实上数据没有被插入,

但是如果我添加大括号,请使用new Customer(id, "name"){}并执行

 using (var db = new EfContext("name=EfSample"))
 {
    db.Customers.Add( new Customer(id, "name"){} );
    db.SaveChanges();
 }

然后实际上将插入数据,

似乎Curly Brackets有所作为,我想只有在添加Curly Brackets时,实体框架才会认识到这是一个真实的具体数据。