Reputation: 853
In my application I create an userControl, and then I need to save it to the database. Here is my method, where I'm saving my userControl :
private void SaveControl(byte userControlType, ISelectableViewModel viewModel, Guid guid)
{
var context = new EntitiesNew();
var instrumentSettings = new INSTRUMENTSETTINGS
{
USERCONTROL = userControlType,
INSTRUMENTHEIGHT = (float)viewModel.InstrumentHeight,
INSTRUMENTWIDTH = (float)viewModel.InstrumentWidth,
INSTRUMENTSCALABLEVALUE = viewModel.ScalableValue,
INSTRUMENTPOSTOLEFT = (float)viewModel.InstrumentPosToLeft,
INSTRUMENTPOSTOTOP = (float)viewModel.InstrumentPosToTop,
INSTRUMENTZINDEX = viewModel.ZIndex,
CREATED_BY= guid
};
context.INSTRUMENTSETTINGSs.Add(instrumentSettings);
context.SaveChanges();
viewModel.ControlId = instrumentSettings.INSTRUMENTSETTINGSID;
var roomId = (from room in context.ROOMs
where room.ROOMNAME == viewModel.RoomName
select room.ROOMID).FirstOrDefault();
var roomWithInstrument = new ROOMWITHINSTRUMENT
{
CREATED_BY = guid,
INSTRUMENTSETTINGSID = viewModel.ControlId,
ROOMID = roomId
};
context.ROOMWITHINSTRUMENTs.Add(roomWithInstrument);
context.SaveChanges();
}
There are no errors, and it's working. The only problem is, that when I'm saving for the first time record to database, it's taking too long (like 2 seconds). After first saving it's working better(less then a second). So my question is - how can I improve first saving, so it will be saving faster?
Upvotes: 2
Views: 1812
Reputation: 127543
First of all you should be putting your context in a using
block
private void SaveControl(byte userControlType, ISelectableViewModel viewModel, Guid guid)
{
using(var context = new EntitiesNew())
{
var instrumentSettings = //...
//...
context.SaveChanges();
}
}
If you don't do that you are not releasing the connections back to the connection pool when you are done and it can cause performance issues for you as your program runs.
On to your actual problem: Entity Framework does a lot of extra "stuff" the first time per AppDomain it connects to a database. You are seeing it happen the first query you call, however you can make it happen sooner.
public static void InitializeDatabaseConnection()
{
using(var context = new EntitiesNew())
{
context.Database.Initialize(false);
}
}
That method will initialize the connection for the current AppDomain and allow the first query to be faster. I would just run this method inside a task at the start of your program.
public static void Main(string[] args)
{
//Assumes you put the function inside the EntitiesNew class
Task.Run(() => EntitiesNew.InitializeDatabaseConnection());
Application.Run(new Form1());
}
Upvotes: 3