更新列表到数据库 [英] Update List into database

查看:66
本文介绍了更新列表到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人,
我创建了一个类 Emp ,其属性与数据库中表的相同列名称相同.然后我将列表声明为

Dear all,
I create a class Emp with properties same columns name of a table in database. Then i declare a List as

Dim lst As New List(Of Emp)

.
我运行项目并在 lst 中插入,更新,删除项目.我想一次将已更改为表的数据保存到数据库中.
请帮我!

P/S:我正在使用LINQ来做.

.
I run project and insert, update, delete items in lst. I want to save data which has changed into table in database in one time.
Pls help me!

P/S: I am using LINQ to do.

推荐答案

然后,您将不得不编写代码以对照数据库中存储的每个记录来检查每个记录,然后采取适当的措施.您将无法使用LINQ进行此操作.

您可能需要向Emp类中添加某种脏"标志,以及一个说明对对象执行了什么操作的字段,例如添加",删除",更改".然后,您可以快速扫描对象列表,并确定要对每个记录(如果有的话)进行什么操作以使其与数据库同步.这样可以避免您不得不为列表中的每个记录查询数据库.


由于Emp类只是数据库中字段的直接反映,因此您可以使用DataTable完成相同的工作,而仅使用DataAdapter对象为您完成所有工作.
Then you''ll have to write the code to check each record against the one stored in the database, then take appropriate action. You won''t be able to use LINQ to do this.

You might want to add some kind of "dirty" flag to your Emp class as well as a field that explains what was done to the object, such as Added, Deleted, Changed. Then you could quickly scan the object list and determine what has to be done for each record, if anything, to sync it up with the database. This would prevent you from having to consult the database for every single record in the List.


Since your Emp class is just a direct reflection of the fields in a database, you could have done the same job with a DataTable instead and just used a DataAdapter object to do all the work for you.


非常感谢!
我在这里编码:
Thanks much!
I code here:
For i As Integer = 0 To lst.Count - 1
    Dim t = New Emp() With
        {
            .Code= lst.Item(i).Code,
            .Name = lst.Item(i).Name,
        }
    db.Emp.Attach(t, True)
    db.Refresh(Data.Linq.RefreshMode.KeepCurrentValues, t)
Next
db.SubmitChanges()


它显示错误:无法添加具有已在使用中的键的实体


It show error: Cannot add an entity with a key that is already in use


这篇关于更新列表到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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