Bis*_*han 21 asp.net detailsview entity-framework-4.1
我正在使用Entity Framework开发ASP.net应用程序.我正在使用DetailsView将数据插入数据库.有一个表Client,其主键是client_id.client_id是由数据库自动生成的.我需要client_id在将记录插入Client表格后将其自动生成并将其分配给隐藏字段以供将来使用.
我搜索了这个,我找到了很多解决方案.但我不知道如何使用它们,因为我是asp.net的新手.我发现Entity Framework在调用后自动使用db生成的值填充业务对象SaveChanges().我的问题是我应该在我的部分课程中将其称为何处?活动是什么?
我正在使用DetailsView和EntityDataSource并将EntityDataSource直接与实体模型绑定,所以我不是要创建插入数据的对象.
STL*_*Dev 43
在调用之后_dbContext.SaveChanges(),实体将自动使用其新的标识字段值进行更新.
以下代码假定您的Entity Framework实体容器名称是MyEntities,并且您的数据库的Client表至少包含以下两个字段:
client_id int identity
client_name varchar(25)
Run Code Online (Sandbox Code Playgroud)
您的代码可能如下所示:
// Establish DbContext
private readonly MyEntities _dbContext = new MyEntities();
// Create new client table entity and initialize its properties
var clientEntity = new Client { client_name="MyCo" };
// Add it to the ORM's collection of Client entities
_dbContext.Clients.Add(clientEntity);
// Save the new entity to the database
_dbContext.SaveChanges();
// Return the identity field from the existing entity,
// which was updated when the record was saved to the database
return clientEntity.client_id;
Run Code Online (Sandbox Code Playgroud)
这就是我正在寻找的。
在部分班级
protected void clientDataSource_OnInserted(object sender, EntityDataSourceChangedEventArgs e )
{
int newPrimaryKey = ((Client)e.Entity).ClientId;
Debug.WriteLine(" Client ID is " + newPrimaryKey);
}
Run Code Online (Sandbox Code Playgroud)
并在 aspx 页面中添加以下行EntityDataSource。
OnInserted="clientDataSource_OnInserted"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62745 次 |
| 最近记录: |