简体   繁体   中英

Asp.Net Entity Framework textbox to database

New to this.

I have a database, one table "Logins":

FirstName, LastName, Birthdate, Email

I am using VS2015 and I am using Entity Framework 6 and have my database loaded in through there. I have text boxes and I want the data entered in them to insert into the table "Logins" when submit is clicked.

I've been looking online and watching videos an I just seem to be getting more confused. How do I do this?

This is what I have on the back end code (the front just has the textboxes and submit button):

 protected void btnSubmit_Click(object sender, EventArgs e)
    {

        using (LoginData2Entities lg = new LoginData2Entities())
        {

            DateTime birthdate = DateTime.Parse(tbBirth.Text);

            Logins l = new Logins();
            l.FirstName = tbFirstName.Text;
            l.LastName = tbLastName.Text;
            l.Birthdate = birthdate;
            l.Email= tbEmail.Text;


            lg.SaveChanges();


        }

Nothing is saving to the database. How do I fix this?

You are not adding the Login object l with your LoginData2Entities object so there is nothing to save into the database.. add this in your code.

lg.Logins.Add(l);

it will look like this..

using (LoginData2Entities lg = new LoginData2Entities())
        {

            DateTime birthdate = DateTime.Parse(tbBirth.Text);

            Logins l = new Logins();
            l.FirstName = tbFirstName.Text;
            l.LastName = tbLastName.Text;
            l.Birthdate = birthdate;
            l.Email= tbEmail.Text;
            lg.Logins.Add(l);
            lg.SaveChanges();

        }

you are not adding the object to database before performing savechanges..

 using (LoginData2Entities lg = new LoginData2Entities())
        {

            DateTime birthdate = DateTime.Parse(tbBirth.Text);
            Logins l = new Logins();
            l.FirstName = tbFirstName.Text;
            l.LastName = tbLastName.Text;
            l.Birthdate = birthdate;
            l.Email= tbEmail.Text;
            lg.Logins.Add(l); //add the object 
            lg.SaveChanges();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM