我有以下表格:实体框架数据建模:2个外键和主键
public class Event {
public int Id {get;set;}
}
public class Participant{
public int Id {get;set;}
}
public class Registration{
public int Id {get;set;}
public int EventId {get;set;}
public int PaticipantId {get;set;}
}
我的注册ID作为主键,但如何确保该事件ID和particpantid是独特?我想到了复合键,但是我需要在注册时使用Id属性,因为我需要将它作为另一个类/表的外键。
约我的DbContext人好奇的是这样的:
modelBuilder.Entity<Registration>()
.HasRequired(e => e.Participant)
.WithMany(u => u.Events)
.HasForeignKey(e => e.ParticipantId);
modelBuilder.Entity<Registration>()
.HasRequired(e => e.Event)
.WithMany(u => u.Participants)
.HasForeignKey(e => e.EventId);
你想组合eventId和participantId是唯一的吗?数据库中这两列的唯一键将保证这一点,或者这不是你要求的吗? – HansVG
你在谈论复合键吗?我在想,但我需要一个单独的唯一身份证,除了他们的组合作为一个ID。这就是Registration.Id的用途。但我需要确保EventId和ParticipantId是唯一的。 – gdubs
你的RegistrationId是你的主键。默认情况下,postgres将为此列创建唯一的约束。然后,在EventId和ParticipantId的列上添加一个唯一的密钥(在您的数据库https://www.postgresql.org/docs/9.6/static/indexes- unique.html中)。这样您的registrationId是唯一的,组合EventId,ParticipantId也是唯一的。如果您正在使用实体框架迁移,则可以在您的dbcontext类中指示您希望在这两列上使用唯一键,并让实体框架为您生成迁移(或将其手动添加到迁移) – HansVG