我正在使用实体框架开发一个asp.net应用程序。我正在使用DetailsView将数据插入数据库。客户端有一个表,其主键是client_id。 client_id是由数据库自动生成的。在Client表中插入一个记录后,我需要自动生成client_id,并将其分配给一个隐藏的字段以供将来使用。
我搜索了这个,我发现很多解决方案。但我不会如何使用,因为我是新的asp.net。调用SaveChanges()后,我发现实体框架会自动使用数据库生成的值填充业务对象。我的问题是在我的部分班上我应该在哪里叫什么事件?
我正在使用EntityDataSource的DetailsView,并使用Entity Model直接绑定EntityDataSource。所以我没有创建对象来插入数据。
解决方法
在调用_dbContext.SaveChanges()之后,实体将自动更新其新的标识字段值。
以下代码假定您的实体框架实体容器名称是MyEntities,并且数据库的Client表至少包含以下两个字段:
client_id int identity client_name varchar(25)
您的代码可能如下所示:
// 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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。