本文介绍了使用实体框架模型插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用实体框架模型在我的数据库中插入一些数据,但由于某些未知的原因,它什么也没做.
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();
}
推荐答案
应该是:
context.TableName.AddObject(TableEntityInstance);
地点:
TableName
:数据库中表的名称.TableEntityInstance
:表实体类的实例.
TableName
: the name of the table in the database.TableEntityInstance
: an instance of the table entity class.
如果您的表是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();
}
这是一个活生生的例子:
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();
}
}
这篇关于使用实体框架模型插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!