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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/268885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 20:52:06  来源:igfitidea点击:

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

c#linq

提问by Ebircsa

What's the best way to write a LINQ query that inserts a record and then returns the primary key of that newly inserted record using C# ?

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

采纳答案by James Curran

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);

回答by GeekyMonkey

Any field with AutoGeneratedValue=true will be filled in after that record is submitted to the database by dc.SubmitChanges()

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

回答by kazem

// 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;