views:

1638

answers:

2

I want to add new admin into my database. But it doesn't work it. Please look at the button1_Click event handler, I need to add value in this event.

public partial class Form1 : Form
    {
        protected NetTanitimTestEntities adminNameContext;
        public Form1()
        {
            InitializeComponent();
            adminNameContext = new NetTanitimTestEntities();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ObjectQuery<Admins> adminNameQuery = adminNameContext.Admins;
            dataGridView1.DataSource = adminNameQuery;
            dataGridView1.Columns["id"].Visible = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {

            using (NetTanitimTestEntities newadmin = new NetTanitimTestEntities())
            {
                Admins admin = new Admins { Name = "ali", SurName = "Çorlu", Username = "acorlu", Password = "1234", UserType = "user" };
                newadmin.SaveChanges();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            adminNameContext.SaveChanges();
        }
    }
+3  A: 

I must admit, I don't know a whole bunch about the Entity Framework but, in your button1 click event you are creating your new entity but you are then just call SaveChanges but you haven't added the new Admins entity to the NetTanitimTestEntities context. So, I would gather because the NetTanitimTestEntities context you are using is unaware of the new entity you have created, nothing is persisted to the database. So, if you add this new Admins entity to the context and then call SaveChanges, hopefully it will then be persisted to your DB.

KnackeredCoder
+8  A: 

It looks like you need to add the following command into you code:

using (NetTanitimTestEntities newadmin = new NetTanitimTestEntities())
{
     Admins admin = new Admins { Name = "ali", SurName = "Çorlu", Username = "acorlu", Password = "1234", UserType = "user" };
     newadmin.AddToAdmins(admin);
     newadmin.SaveChanges();
}

or something like that depending on the actual name of the generated method. Your "newadmin" object should have a bunch of "add" methods generated for each entity you have in your model.

Alex Konduforov