简体   繁体   English

如何使用LINQ和C#插入记录并返回该记录的主键

[英]How to insert a record with LINQ and C# and return the Primary Key of that record

编写插入记录然后使用C#返回新插入记录的主键的LINQ查询的最佳方法是什么?

The primary key value will be in that property after the SubmitChanges(). 主键值将在SubmitChanges()之后的该属性中。

MyTable record = new MyTable();
record.Name = "James Curran";
db.MyTable.InsertOnSubmit(record);
db.SubmitChanges();
Console.WriteLine("record inserted as ID : {0}", record.Id);
// 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();
}
return ord.OrderID;

任何具有AutoGeneratedValue = true的字段将在dc.SubmitChanges()将该记录提交到数据库后填写

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM