我正在尝试使用Entity Framework模型在数据库中插入一些数据,但是由于某些未知的原因,它什么也不做。
我在这里想念什么吗?
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
如果您的表是Orders,则:
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(); } }