Linq to Sql
-
Hi I wanna Insert a record into the database by fetching the current user and current date.I have to do this by Linq to sql..As I'm new to this can some one tell me how to do this?? user us= new user(); us.Date = DateTime.Now; us.name =""; dc.users.InsertOnSubmit("us"); Is this the right way to do?? us.name should be the login name..how to fetch the user name from db??
-
Hi I wanna Insert a record into the database by fetching the current user and current date.I have to do this by Linq to sql..As I'm new to this can some one tell me how to do this?? user us= new user(); us.Date = DateTime.Now; us.name =""; dc.users.InsertOnSubmit("us"); Is this the right way to do?? us.name should be the login name..how to fetch the user name from db??
sindhuan wrote:
Is this the right way to do??
No, because
dc.users.InsertOnSubmit("us");
won't even compile, because you're trying to insert a string "ur". Your code is expecting an entity of type user. So you want
dc.users.InsertOnSubmit(us);
So, you first want to query the user to get the name, then insert the new row.
using (MyDataContext dc = new MyDataContext())
{
var userName = (from u in dc.tblUsers
where u.Id = someId
select u.UserName).FirstOrDefault();user us = new user { Date = DateTime.Now, name = userName }; try { dc.users.InsertOnSubmit(us); } catch(Exception e) { // Handle exception here }
}
You will have to adjust the data context and table names and column names, but this should get you started.
If it's not broken, fix it until it is