Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
Hello all I have a C# WPF project and I added Entity Framework to it with a ADO.net data model. I have a .mdf database with a table in it and data. When I call the data.ToList() method I get the correct data from my db into my datagrid. So that is correct. The issue I am having is when I go to create/insert a new file into the database the record does not get saved. I also get 0 errors. I been reading online for hours trying to figure this out and so far all I came up with is maybe its because of my connection string because I have |data directory| or something like that it is maybe? I can also load the user into the screen when I send the selected user to the next screen I have created. Just cannot figure out why my user will not save to the database.

C#
//connstring –
<connectionStrings>
    <add name="EFcontext" connectionString="metadata=res://*/EFModel.csdl|res://*/EFModel.ssdl|res://*/EFModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\EntityFramewordDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
  </connectionStrings>
public class CRUD
    {
        //get the entity framework model context that was created.
        private EFcontext framework = null;

        public CRUD()
        {
            framework = new EFcontext();
        }

        public Person GetPersonById(int personId)
        {
            return framework.People.Find(personId);
        }

        public List<Person> GetAllPeopleByList()
        {
            return framework.People.ToList();
        }

        public void CreatePerson(Person person)
        {
            if(person != null)
            {
                framework.People.Add(person);
                framework.SaveChanges();
            }
        } public partial class MainWindow : Window
    {
        private CRUD entityFramework;
        private Person dataGridPerson;

        public MainWindow()
        {
            InitializeComponent();
            entityFramework = new CRUD();
            PopulateDataGrid();
        }

        private void PopulateDataGrid()
        {
            DataGridPeople.ItemsSource = entityFramework.GetAllPeopleByList();
        }

        private void BtnCreate_Click(object sender, RoutedEventArgs e)
        {
            Window CreatePerson = new CreateUpdateWindow();
            CreatePerson.Show();
            Close();
        } public partial class CreateUpdateWindow : Window
    {
        private CRUD entityFramework;
        private Person personWindowObject; 							public CreateUpdateWindow()
        {
            InitializeComponent();
            entityFramework = new CRUD();

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            Person personObject = new Person();
            Window mainWindow = new MainWindow();                    DateTime dateNow = DateTime.Now;
                    personObject.DateCreated = dateNow;
                    entityFramework.CreatePerson(personObject);
                    MessageBox.Show("Created new person.", "Created");
                    mainWindow.Show();
                    Close();
                }
            
}
//copied all sections of my code what is being used for creating user and to add 2 db


What I have tried:

looking online for hours trying different ways maybe connstring problem unsure?
Posted
Updated 16-Nov-18 2:36am

1 solution

Your MainWindow constructor binds the grid to the current records in the database.

Your BtnSave_Click method creates a new MainWindow instance before adding the new record to the database.

Therefore, your main window can't show the new record, because it doesn't exist at the point the data was loaded.

Try moving the line that creates the new MainWindow instance after the CreatePerson call:
C#
private void BtnSave_Click(object sender, RoutedEventArgs e)
{
    Person personObject = new Person();
    DateTime dateNow = DateTime.Now;
    personObject.DateCreated = dateNow;
    // TODO: You probably want to set some other properties here...
    entityFramework.CreatePerson(personObject);
    MessageBox.Show("Created new person.", "Created");
    
    Window mainWindow = new MainWindow();                    
    mainWindow.Show();
    Close();
}
 
Share this answer
 
Comments
TheBigBearNow 17-Nov-18 3:15am    
That worked exactly like you said to do! Now the database adds the new records while the project is running and i can update them and everything BUT now when i close the project NOTHING IS SAVED. everytime i restart the project it starts from the beginning. The project works and saves while running but then when i restart to keepp adding on it always starts over and does not save what i did?
thank you if you have any input
Richard Deeming 19-Nov-18 8:11am    
It sounds like your context is set to delete and recreate the database on each run.

Either that, or you've got a database file as part of your project, and it's set to always overwrite the file in the output directory.
TheBigBearNow 17-Nov-18 20:07pm    
In EF it looks like i have to of state.added or create and state.modified for update like :

[code]
public void CreatePerson(Person person)
{
if(person != null)
{

framework.People.Add(person);
framework.Entry(person).State = System.Data.Entity.EntityState.Added;
framework.SaveChanges();
}
}
[/code]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900