Home > other >  C# - Can't access data from a simple, 1-table mdf database that I have just created with anothe
C# - Can't access data from a simple, 1-table mdf database that I have just created with anothe

Time:06-23

From the program that created the file (DB_Write), I am able to access and query the data easily. I wanted to see if I could read the file and manipulate the data from another simple C# program (DB_Read). DB_Read is able to find the database with the connectionString and open the connection successfully but my statement, "var DatabaseExists = context.data.Any(); fails ever time. I've spent days searching the net for some clue but without success, which makes me think that I am overlooking something very simple and obvious. DB_Read is made up of parts that I cut and pasted directly from DB_Write (database class, database context and column names). I've include the full program below. What am I missing here?

...

using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
using System.Data.SqlClient;


namespace DB_Read
{
  public partial class Form1 : Form
  {
    public Form1()
    {
    InitializeComponent();
    }
   

    public class TestDB
    {
       [Key]public int Index { get; set; }
         
        public string Letter { get; set; }

        public Double WTime { get; set; }
    }

    public class TestDB_Context : DbContext
    {
       public DbSet<TestDB> data { get; set; }
    }


    private void btnSum_Click(object sender, EventArgs e)
    {
       string connectionString; 

       SqlConnection cnn;

       connectionString = @"Data Source=(localdb)\mssqllocaldb;
                            Initial Catalog=DB_Write.Form1 TestDB_Context;
                            Integrated Security=True";

       cnn = new SqlConnection(connectionString);

       cnn.Open();

       using (var context = new TestDB_Context())
       {
          var DatabaseExists = context.data.Any();

          if(DatabaseExists == true)
          {
             var query = (from column3 in context.data
                          select column3.WTime).Sum();

             txtResult.Text = Convert.ToString(query);
          }
       }

       cnn.Close();
    }
  }
}

...

CodePudding user response:

Your SqlConnection (cnn) is doing nothing. It's not being used by anything.

you should have something like

public class TestDB_Context : DbContext
{
   public TestDB_Context(string connectionString) : base(connectionString) 
   {}

   public DbSet<TestDB> data { get; set; }
}

and then

private void btnSum_Click(object sender, EventArgs e)
{
   string connectionString = @"Data Source=(localdb)\mssqllocaldb;
                        Initial Catalog=DB_Write.Form1 TestDB_Context;
                        Integrated Security=True";

   using (var context = new TestDB_Context(connectionString))
...
  • Related