不同的 C# 应用程序通过 Linq to Entities 访问数据库
我有一个 C# 控制台应用程序,它执行一些处理,然后写入数据库。我将其部署在具有不同配置设置的服务器上多次,以执行略有不同的操作。但是,它们都必须使用 Linq to Entities 写入同一数据库(并且可能需要将相同的数据插入到同一个表中,如果该表尚不存在)。
如果我使用线程,我可以锁定方法,或者存储过程,我可以将写入排队以避免冲突,但是有什么方法可以将它们保留为单独的应用程序,并防止它们都尝试将相同的内容写入数据库同时?
当发生冲突时,我经常会遇到例外情况。
编辑:
我不一定要尝试调试为什么会出现异常,而是更多地寻找“最佳实践”方法的建议,例如是否应该在控制台应用程序级别处理此问题、L2E 级别或数据库级别。
I have a C# console application which does some processing and then writes to the database. I have it deployed multiple times on a server with different config settings to do slightly different things. However, they all have to write to the same database (and may need to insert the same data into to the same table if it doesn't already exist) using Linq to Entities.
If I were using threads I could lock the method, or stored procedures I could queue up the writes to avoid clashes, but is there any way to keep these as seperate applications, and prevent them both trying to write the same thing to the database at the same time?
I'm getting an exception every so often when there is a conflict.
Edit:
I'm not necessarily trying to debug why I'm getting the exception, looking more for any suggestions of a 'best practice' way of doing this e.g. Should this be handled at the console app level, the L2E level, or the database level.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不能以高隔离级别启动事务,以便锁在服务器端处于活动状态?
Why can't you start a transaction with high isolation level so that the lock is active at the server side?
您可以使用锁(悲观并发模型)或时间戳(乐观并发模型)来处理并发问题。
这是一个非常广泛的主题,因此我建议您首先通过谷歌搜索数据库并发性。
You may use locks (pessimistic concurrency model) or timestamps (optimistic concurrency model) to deal with concurrency issues.
It is a very wide topic so i would suggest you start by googling for database concurrency.