使用LinqToSql插入

时间:2012-12-17 16:22:21

标签: c# asp.net sql-server linq-to-sql

insert into table1 (Wicket, Run, Catch) 
values (Wicket + 2, Run + 22, Catch + 5)

此语句用于使用存储过程插入数据。

如何在不使用存储过程但使用LinqToSql的情况下以相同方式插入数据?

它的代码是什么?

3 个答案:

答案 0 :(得分:1)

var db = new NorthwindDataContext();
// Create a new Order object.
Order ord = new Order
{
    OrderID = 12000,
    ShipCity = "Seattle",
    OrderDate = DateTime.Now
    // …
};

// Add the new object to the Orders collection.
db.Orders.InsertOnSubmit(ord);

// Submit the change to the database.
try
{
    db.SubmitChanges();
}
catch (Exception e)
{
    Console.WriteLine(e);
    // Make some adjustments.
    // ...
    // Try again.
    db.SubmitChanges();
}

答案 1 :(得分:1)

这样的事情:

using(var context = new YourContext())
{
 var table1 = new table1(){ //fill out properties };
 context.table1.InsertOnSubmit(table1);
 context.SubmitChanges();
}

答案 2 :(得分:0)

请参阅MSDN:http://msdn.microsoft.com/en-us/library/bb386941.aspx

// Create a new Order object.
Order ord = new Order
{
    OrderID = 12000,
    ShipCity = "Seattle",
    OrderDate = DateTime.Now
    // …
};

// Add the new object to the Orders collection.
db.Orders.InsertOnSubmit(ord);

// Submit the change to the database.
try
{
    db.SubmitChanges();
}
catch (Exception e)
{
    Console.WriteLine(e);
    // Make some adjustments.
    // ...
    // Try again.
    db.SubmitChanges();
}