[英]Rewriting LINQ to SQL class using DataContext
I have written a function to insert some data into SQL table based on the data received from the client iny my LINQ to SQL class: 我编写了一个函数,根据从我的LINQ to SQL类客户端收到的数据将一些数据插入到SQL表中:
//some code
string commString = "INSERT INTO Token (tk_ID, tk_token, tk_date, tk_IP) VALUES (@val1, @val2, @val3, @val4)";
string conString = "placeholder";
token = GenerateToken(clientLoginData);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand com = new SqlCommand())
{
com.Connection = con;
com.CommandText = commString;
com.Parameters.AddWithValue("@val1", clientLoginData.cl_ID);
com.Parameters.AddWithValue("@val2", token);
com.Parameters.AddWithValue("@val3", clientLoginData.LoginTime);
com.Parameters.AddWithValue("@val4", clientLoginData.cl_IP);
try
{
con.Open();
com.ExecuteNonQuery();
}
catch (SqlException e)
{
}
}
//rest of function
Is this the correct way to do so? 这是正确的方法吗? I heard you can do it much easier using
我听说你可以更轻松地使用它
SampleDBDataContext dc = new SampleDBDataContext();
and then using this variable dc. 然后使用这个变量dc。 I never used it however, is it true?
我从来没用过它,是真的吗? And can someone give me example of inserting one value into the table using this?
有人可以给我一个使用这个插入一个值到表中的例子吗?
your code is a simple c# code to insert value and not Linq2Sql for Linq2Sql you should have 你的代码是一个简单的c#代码,用于插入值而不是Linq2Sql,你应该拥有Linq2Sql
using (YourDbContext dc=new YourDbContext ()){
Token item = new Token();
item.tk_date = clientLoginData.LoginTime;
item.tk_IP = clientLoginData.cl_IP;
item.tk_ID = clientLoginData.cl_ID;
item.tk_token = token;
dc.Tokens.InsertOnSubmit
dc.SubmitChanges();
}
Do like this: 这样做:
DataContext dc = new Using(DataContext(Connections.GetDynamicConnectionfromConfig()))
{
Sampleclass obj = new Sampleclass();
//Here assign properties to obj
dc.tableName.InsertOnSubmit(obj);
dc.SubmitChanges();
}
Hope this will help you. 希望这会帮助你。
your code should look like this 你的代码应该是这样的
using (SampleDBDataContext dc = new SampleDBDataContext())
{
Token item = new Token();
item.tk_ID = clientLoginData.cl_ID;
item.tk_token = token;
item.tk_date = clientLoginData.LoginTime;
item.tk_IP = clientLoginData.cl_IP;
dc.Tokens.InsertOnSubmit(item);
dc.SubmitChanges();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.