So I have the following models
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Appointment
{
public int Id { get; set; }
public string Name{ get; set; }
}
and I want them assigned to a another table with a separate primary key like so
public class UserAppointment
{
public int Id { get; set; }
public int UserId { get; set; }
public int AppointmentId { get; set; }
public virtual Appointment Appointment {get;set;}
public virtual User User {get;set;}
}
What I wanted is the Id be a key (unique, auto generate, etc) while at the same time will force the UserId and AppointmentId to have a unique combination as well.
eg
this is what i want
Id UserId AppointmentId
1 1 2
2 1 3
and not this
Id UserId AppointmentId
1 1 2
2 1 2
3 1 2
At the moment I did some modelbuilder statements on my context to configure my keys
modelbuilder.Entity<UserApointment>()
.HasRequired(e => e.User)
.HasMany(u => u.Appointment)
.HasForeignKey(e => e.UserId);
modelbuilder.Entity<UserApointment>()
.HasRequired(e => e.Appointment)
.HasMany(u => u.Users)
.HasForeignKey(e => e.AppointmentId);
But it will still let me insert records with similar user and appointment ids.
Any advice on how to deal with this is very much appreciated!
Thanks!!
You can tackle this at the database level by simply creating a unique constraint on the UserAppointment table.
On Entity Framework (which I am not familiar with) seems to be done like this:
Read more here., specially the remark:
UPDATE
Probably a Unique Index serves your purposes better:
This unique index will ensure that no duplicate combination of UserId and AppointmentId will ever exist in the table and will also speed up your queries.