I have a windows form C # application and I run the context on the form's load, and I didn't create the base data unless you save a record to an entity.
How can I get EF 6 to create the database for me, without necessarily having to save a data?
With this code I do NOT create the database. Note that the Add and SaveChanges lines are commented
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CodeFirstDBCreation
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
//Creando base de datos
CodeFirstContext objContext = new CodeFirstContext();
// Creando Objeto compañia.
Company objCompany = new Company();
objCompany.Name = "MONTANA";
// objContext.Companies.Add(objCompany);
// objContext.SaveChanges();
}
}
}
With this code it creates the database for me. Note that the Add and SaveChanges lines are no longer commented.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CodeFirstDBCreation
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
//Creando base de datos
CodeFirstContext objContext = new CodeFirstContext();
// Creando Objeto compañia.
Company objCompany = new Company();
objCompany.Name = "MONTANA";
objContext.Companies.Add(objCompany);
objContext.SaveChanges();
}
}
}
This is my entity
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirstDBCreation
{
[Table("EMPRESA")]
class Company
{
[Key]
public int CompanyId
{
get;
set;
}
public String Name
{
get;
set;
}
public String Sexo
{
get;
set;
}
public int Edad
{
get;
set;
}
public int Edad2
{
get;
set;
}
}
}
This is my connection string
<connectionStrings>
<add name="CompanyConnectionString" connectionString="Data Source=LAPTOP-6BGM1RKA\SQLEXPRESS;Initial Catalog=Company;Pooling=false;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>