Click here to Skip to main content
15,503,737 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have created session and also tables in db
i just wanna store who creates or manipulates the data when a user logged in.

when a user exists then from the log in -session it takes username and should store in the table at createdby

how can i store the session["createdby"] from code to createdby in sql server
from controller to db in data first approach mvc5.

im using entity framework,mvc5

What I have tried:

public ActionResult Create([Bind(Include = "Id,FirstName,Lastname,Contact,Address,Course,DOJ,Username,Password,Timestamp,createdby")] tbluser tbluser)
        {
            if (ModelState.IsValid)
            {
                db.tblusers.Add(tbluser);
                db.SaveChanges();
                Session["Userid"] = tbluser.Id;
                Session["createdby"] = tbluser.Username.ToString();
                string created = Session["createdby"].ToString();
                int id = (int)Session["Userid"];
                insertUsername(created, id);
                return RedirectToAction("Index");
            }

            return View(tbluser);
        }


what i have tried using query but mostly i might have given it wrong in entity framework. if anyone can notice please let me know
public void insertUsername(string createdby, int id)
       {
           try
           {
               string connection = ConfigurationManager.ConnectionStrings["SchoolManagerEntitiesA"].ConnectionString;
               EntityConnection con = new EntityConnection(connection);
               EntityCommand command = new EntityCommand("UPDATE tbluser SET createdby=@createdby WHERE Id= @id", con);
               con.Open();
               command.Parameters.Add("id", DbType.Int32).Value = id;
               command.Parameters.Add("createdby", DbType.String).Value = createdby;
               command.ExecuteNonQuery();
               con.Close();
           }
           catch (Exception ex)
           {

               throw;
           }
       }


Table given below where i store
CREATE TABLE tbluser(
    [Id] [int] IDENTITY(1,1) NOT NULL Primary Key,
    [FirstName] [nvarchar](50) NULL,
    [Lastname] [nvarchar](50) NULL,
    [Contact] [bigint] NULL,
    [Address] [nvarchar](250) NULL,
    [Course] [nvarchar](50) NULL,
    [DOJ] [datetime] NULL,
    [Username] [nvarchar](50) NOT NULL,
    [Password] [nvarchar](50) NOT NULL,
    [Timestamp] [datetime] NULL,
Createdby varchar(50) not null)
Posted
Updated 25-Aug-22 4:17am
v4

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



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