问题
Please anybody help me to Insert created date(now) and created by(username) in asp.net5. whenever I create the new record in crud application the above records should be entered automatically in database.
regards arun sahani
回答1:
It is nothing to do with MVC or any technology. You will have to either pass these values from UI or use SQL Default values to populate
CreateUserId nvarchar(55) NOT NULL CONSTRAINT [DF_Table_CreateUserId] DEFAULT suser_sname()
Use suser_sname
only in those cases where you perform your operations from UI to DB with the logged-in user credentials. In most of the web apps, it is not the way, so you may end up passing the actual your name or your user id to database like any other fields you pass for that table.
For timestamp, you can fairly use this Default value
CreateDateTime DateTime NOT NULL DEFAULT GETDATE()
This will automatically populate created time stamp whenever you insert values into that table. You don't need to pass any value for this column while inserting. You can optionally pass value, if you want to insert some other value from UI.
Let us say for example, you don't set DEFAULT values in fields; you can certainly pass values from UI to populate those fields; What happens when someone inserts a row directly into table without going through UI Process? May be a an Admin inserting a row? You need to consider all those scenarios.
来源:https://stackoverflow.com/questions/36922291/insert-created-datenow-and-created-byusername-in-asp-net-mvc-5