Click here to Skip to main content
15,907,687 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)
                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)
               string connection = ConfigurationManager.ConnectionStrings["SchoolManagerEntitiesA"].ConnectionString;
               EntityConnection con = new EntityConnection(connection);
               EntityCommand command = new EntityCommand("UPDATE tbluser SET createdby=@createdby WHERE Id= @id", con);
               command.Parameters.Add("id", DbType.Int32).Value = id;
               command.Parameters.Add("createdby", DbType.String).Value = createdby;
           catch (Exception ex)


Table given below where i store
    [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)
Updated 25-Aug-22 3:17am

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