如何返回新创建的对象的键。 [英] How do I return a the key of a newly created object.

查看:102
本文介绍了如何返回新创建的对象的键。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的对象存储在数据库中,标识列为ID。当对象由上下文创建时,我想返回该ID。我将如何实现这一目标?

解决方案

James,

我不确定我的问题是否正确,但这是我最好的回答:< br>
在默认情况下,每次调用SaveChanges()以插入新实体时,Entity Framework将生成相应的SQL以在每次插入后检索标识的值。获得的值将用于填充新保存的权限中的关键属性。

这不适合你吗?也许这会有所帮助:

在数据库模式中定义身份密钥并使用创建模型的默认方式时(即在项目中添加了ADO.NET实体数据模型项并对模式进行了逆向工程形成数据库),您的模型将包括StoreGeneratedPattern =" Identity" SSDL部分的属性。例如:




























< EntityType 名称 = " Categories" >
< >
< PropertyRef 名称 = " CategoryID" />
< font style ="color:blue">< / > < font style ="font-size:11px">
< 属性 名称 = " CategoryID" Type = " int" Nullable = " false" StoreGeneratedPattern = " Identity" />
< 属性 名称 = " CategoryNam e" 类型 = " nvarchar" Nullable = " false" MaxLength = " 15" />
< 属性 名称 = " CreationDate" Type = & quot; datetime" />
< Property 名称 = " Description" 类型 =  " />
< Property 名称 = " LastEditDate" Type = " datetime" />
< 属性 名称 = " Picture" Type = " image" />
< / EntityType >

My objects are stored in the database with an identity column as the ID. I'd like to return that ID when the object is creating by the context. How would I achieve this?

解决方案

James,

Not sure I am getting your question right, but here is my best try to answer: 

In the default case, every time you invoke SaveChanges() to insert new entities, Entity Framework will generate the the appropriate SQL to retrieve the values of the identities after each insert. The obtained value will be used to populate the key properties in the newly saved entitiy.

Is this not working for you? Perhaps this will help:

When you define identity keys in your database schema and you use the default way of creating a model (i.e. you added an ADO.NET Entity Data Model item in your project and reverse engineered the schema form the database), your model will include the StoreGeneratedPattern="Identity" attribute on the SSDL section. For instance:

<EntityType Name="Categories">  
  <Key> 
    <PropertyRef Name="CategoryID" /> 
  </Key> 
  <Property Name="CategoryID" Type="int" Nullable="false" StoreGeneratedPattern="Identity" /> 
  <Property Name="CategoryName" Type="nvarchar" Nullable="false" MaxLength="15" /> 
  <Property Name="CreationDate" Type="datetime" /> 
  <Property Name="Description" Type="ntext" /> 
  <Property Name="LastEditDate" Type="datetime" /> 
  <Property Name="Picture" Type="image" /> 
</EntityType> 


这篇关于如何返回新创建的对象的键。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆