简体   繁体   English

如何从表中获取主键而不进行第二次旅行?

[英]How to get the primary key from a table without making a second trip?

How would I get the primary key ID number from a Table without making a second trip to the database in LINQ To SQL? 如何在进行LINQ To SQL数据库的第二次访问的情况下从表中获取主键ID号?

Right now, I submit the data to a table, and make another trip to figure out what id was assigned to the new field (in an auto increment id field). 现在,我将数据提交到一个表中,并再次进行一次旅行,以确定为新字段分配的id(在自动增量id字段中)。 I want to do this in LINQ To SQL and not in Raw SQL (I no longer use Raw SQL). 我想在LINQ To SQL中执行此操作,而不是在Raw SQL中执行此操作(我不再使用Raw SQL)。

Also, second part of my question is: I am always careful to know the ID of a user that's online because I'd rather call their information in various tables using their ID as opposed to using a GUID or a username, which are all long strings. 此外,我的问题的第二部分是:我总是小心地知道在线用户的ID,因为我宁愿使用他们的ID在各种表中调用他们的信息,而不是使用GUID或用户名,这些都是长的字符串。 I do this because I think that SQL Server doing a numeric compare is much (?) more efficient than doing a username (string) or even a guid (very long string) compare. 我之所以这样做是因为我认为进行数字比较的SQL Server比使用用户名(字符串)甚至是guid(非常长的字符串)比较更有效(?)。 My questions is, am I more concerned than I should be? 我的问题是,我是否比我应该更关心? Is the difference worth always keeping the userid (int32) in say, session state? 差异值是否总是将userid(int32)保持在会话状态?


@RedFilter provided some interesting/promising leads for the first question, because I am at this stage unable to try them, if anyone knows or can confirm these changes that he recommended in the comments section of his answer? @RedFilter为第一个问题提供了一些有趣/有希望的线索,因为我在这个阶段无法尝试它们,如果有人知道或可以确认他在答案的评论部分建议的这些变化?

If you have a reference to the object, you can just use that reference and call the primary key after you call db.SubmitChanges() . 如果您有对该对象的引用,则可以在调用db.SubmitChanges()之后使用该引用并调用主键。 The LINQ object will automatically update its (Identifier) primary key field to reflect the new one assigned to it via SQL Server. LINQ对象将自动更新其(标识符)主键字段,以反映通过SQL Server分配给它的新主键字段。

Example (vb.net): 示例(vb.net):

  Dim db As New NorthwindDataContext
  Dim prod As New Product
  prod.ProductName = "cheese!"
  db.Products.InsertOnSubmit(prod)
  db.SubmitChanges()
  MessageBox.Show(prod.ProductID)

You could probably include the above code in a function and return the ProductID (or equivalent primary key) and use it somewhere else. 您可以在函数中包含上面的代码并返回ProductID(或等效的主键)并在其他地方使用它。

EDIT: If you are not doing atomic updates, you could add each new product to a separate Collection and iterate through it after you call SubmitChanges. 编辑:如果您没有进行原子更新,您可以将每个新产品添加到单独的集合中,并在调用SubmitChanges后迭代它。 I wish LINQ provided a 'database sneak peek' like a dataset would. 我希望LINQ像数据集一样提供“数据库偷看”。

Unless you are doing something out of the ordinary, you should not need to do anything extra to retrieve the primary key that is generated. 除非您正在做一些与众不同的事情,否则您不需要做任何额外的事情来检索生成的主键。

When you call SubmitChanges on your Linq-to-SQL datacontext, it automatically updates the primary key values for your objects. 在Linq-to-SQL datacontext上调用SubmitChanges时,它会自动更新对象的主键值。

Regarding your second question - there may be a small performance improvement by doing a scan on a numeric field as opposed to something like varchar() but you will see much better performance either way by ensuring that you have the correct columns in your database indexed. 关于你的第二个问题 - 通过对数字字段进行扫描而不是像varchar()那样,可能会有很小的性能提升,但是通过确保数据库中的正确列被索引,您将看到更好的性能。 And, with SQL Server if you create a primary key using an identity column, it will by default have a clustered index over it. 并且,对于SQL Server,如果使用标识列创建主键,则默认情况下它将具有聚簇索引。

Linq to SQL automatically sets the identity value of your class with the ID generated when you insert a new record. Linq to SQL使用插入新记录时生成的ID自动设置类的标识值。 Just access the property. 只需进入酒店。 I don't know if it uses a separate query for this or not, having never used it, but it is not unusual for ORMs to require another query to get back the last inserted ID. 我不知道它是否使用了单独的查询,从未使用它,但ORM需要另一个查询来取回最后插入的ID并不罕见。

Two ways you can do this independent of Linq To SQL (that may work with it): 有两种方法可以独立于Linq To SQL(可以使用它):

1) If you are using SQL Server 2005 or higher, you can use the OUTPUT clause: 1)如果您使用的是SQL Server 2005或更高版本,则可以使用OUTPUT子句:

Returns information from, or expressions based on, each row affected by an INSERT, UPDATE, or DELETE statement. 返回受INSERT,UPDATE或DELETE语句影响的每一行的信息或基于表达式的表达式。 These results can be returned to the processing application for use in such things as confirmation messages, archiving, and other such application requirements. 这些结果可以返回到处理应用程序,以用于确认消息,存档和其他此类应用程序要求。 Alternatively, results can be inserted into a table or table variable. 或者,可以将结果插入表或表变量中。

2) Alternately, you can construct a batch INSERT statement like this: 2)或者,您可以构造一个这样的批处理INSERT语句:

insert into MyTable
(field1)
values
('xxx');
select scope_identity();

which works at least as far back as SQL Server 2000. 它至少可以用于SQL Server 2000。

In T-SQL, you could use the OUTPUT clause, saying: 在T-SQL中,您可以使用OUTPUT子句,说:

INSERT table (columns...)
OUTPUT inserted.ID
SELECT columns...

So if you can configure LINQ to use that construct for doing inserts, then you can probably get it back easily. 因此,如果您可以将LINQ配置为使用该构造进行插入,那么您可以轻松地将其恢复。 But whether LINQ can get a value back from an insert, I'll let someone else answer that. 但是,LINQ是否可以从插入中获取值,我会让其他人回答这个问题。

从LINQ调用存储过程返回ID作为输出参数可能是最简单的方法。

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

相关问题 如何将由自动递增创建的一个表中的主键作为外键插入第二个表中? - How to insert primary key from one table which created by auto increment, into a second table as forign key? 如何获取表的PRIMARY KEY COLUMNS(如果是COMPOSITE主键) - How to get PRIMARY KEY COLUMNS of a table (in case of COMPOSITE primary key) 如何获取表的PRIMARY KEY列名 - How to get PRIMARY KEY column name of a table C#实体框架,如何从通过Junction表创建的对象中获取主键 - C# Entity framework, how to get the primary key from an object created from a Junction table 添加模型后,如何在不查询数据库的情况下从模型获取主键? - How to get a primary key from a model without querying the DB once I've added the model? 将数据插入表并从增加的主键中获取ID - Insert data into table and get ID from increased primary key LINQ-to-SQL从表中获取主键 - LINQ-to-SQL get Primary Key from Table 如何将第一个表的主键值更新为第二个表的外键(实体框架代码第一个模型)? - How to update primary key values of first table into foreign keys in the second table (Entity framework code first model)? 如何在没有存储过程的情况下获取更新的行主键 - How to get the updated rows primary key without stored procedure 如何获取表和主键,如果表没有主键,则显示null? - How to get tables and primary key, and display null if the table has no primary key?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM