【问题标题】:How to prevent duplicate records in a mapping table in MVC3?如何防止 MVC3 中映射表中的重复记录?
【发布时间】:2013-02-21 02:29:40
【问题描述】:

我有以下表格:

Client (PKey = ClientId)
User   (PKey = UserId) 

UserClient (FKeys = ClientId, UserId)

当我尝试在 UserClient 表中添加一条记录(映射)以使 User-Client 对应该是唯一的时,它允许重复记录。

我想阻止这种情况。这意味着,当尝试添加现有的用户-客户端对时,它应该抛出客户端验证。

如何防止在 MVC3 的映射表中输入重复记录?

【问题讨论】:

  • 您是否将 UserClient 中的 ClientId 和 UserId 设为主键而不仅仅是外键?
  • 是的,我在 UserClient 表中有一个主键 UserClientId。
  • 这不是 MVC3 的问题。这是一个数据库设计问题。 :-)

标签: duplicates record rdbms


【解决方案1】:

听起来您想唯一标识列。 Yu 可以借助 SQL server 中的 Candidate Key 来实现,但在实体框架中不支持。

Entity Framework: Alternate solution to using non primary unique keys in an association

【讨论】:

    【解决方案2】:

    由于 UserClientId 独立于您设置的外键,因此您将获得重复项。外键仅确保插入到 UserClient 表中的键存在于 User 和 Client 表中。

    如果可能,删除 UserClientId 主键并将您的 ClientId 和 UserId 设置为 UserClient 表的主键。然后,您将处理重复项和外键完整性。

    实体关系图如下所示:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      • 2015-12-04
      • 1970-01-01
      • 2015-07-22
      • 2013-11-11
      相关资源
      最近更新 更多