I wrote a windows service for a project in which I needed to store some data in a database. I created the table with the required columns and created an entity model from the database. Context and mapping are done automatically by VS 2012. In order to test if the data is being saved, I hard coded some values and ran the service but the data doesn't get saved in the database.
Here is a sample service I wrote to test this out:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace serviceWithDatabase
{
public partial class testService : ServiceBase
{
Database1Entities db = new Database1Entities();
public testService()
{
InitializeComponent();
test();
}
protected override void OnStart(string[] args)
{
}
public void test()
{
Table t = new Table();
t.ticker = "goog";
t.Day1 = 1234;
t.Day2 = 4567;
t.Day3 = 7890.56;
db.Tables.Add(t);
db.SaveChanges();
}
protected override void OnStop()
{
}
}
}
model for the table:
namespace serviceWithDatabase
{
using System;
using System.Collections.Generic;
public partial class Table
{
public int Id { get; set; }
public string ticker { get; set; }
public Nullable<double> Day1 { get; set; }
public Nullable<double> Day2 { get; set; }
public Nullable<double> Day3 { get; set; }
}
}
App.config code:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="Database1Entities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
I can manually go into the database via VS 2012 and add data but it won't save data via the windows service. Anyone have any suggestions ?