在外键也是主键的情况下是否可能存在关系? [英] Is it possible to have a relation where the foreign key is also the primary key?

查看:88
本文介绍了在外键也是主键的情况下是否可能存在关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SQL数据库中有一个表,该表应该与两个表之一相关,但不能与两者都有关系.

I have a table in a SQL database which should have a relation with one of two tables, but not both.

我的经理通过使用表Competitor的ID字段作为其他两个表的主键和外键来解决此问题.这些表都没有自动递增的ID.

My manager solved it by using the ID field of the table Competitor as both primary key and as foreign key for the two other tables. None of the tables have autoincremental IDs.

问题是,当我尝试添加新的竞争对手时,除非在其他两个表中都具有指定ID的条目与我想要的相反,否则它将失败.

Problem is, when I try to add a new compeitor, it fails unless there is an entry in both of the other tables with the specified ID, which is the opposite of what I want.

以下是向您展示如何完成的插图:

Here is an illustration to show you how it's done:

很抱歉,如果以前已经发布或回答了此问题.搜索时找不到任何东西.

I am sorry if this has been posted or answered before. I could not find anything while searching.

最好的问候 卡贾克

推荐答案

请确保仅在相关属性"上将键设置为外键"和主键".竞争对手应具有主键.

Sure just set the key as Foreign and Primary on the "dependant properties". The Competitor should have the primary key.

public class Competitor
{
  [Key]
  public int Id { get; set; }
}

public class Equestrain
{
  [Key]
  [ForeignKey("Competitor")]
  public int Id{ get; set; }

  public Competitor Competitor { get; set; }
}

public class TeamEquestrain
{
  [Key]
  [ForeignKey("Competitor")]
  public int Id{ get; set; }

  public Competitor Competitor { get; set; }
}

MSDN-配置必需关系到可选关系(一对零或一个)

这篇关于在外键也是主键的情况下是否可能存在关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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