我正在尝试建立多对多关系。一个客户需要能够拥有许多管理人员,而一个管理部门应该能够拥有许多客户。我的问题:在Microsoft Management Studio中,以某种方式将ClientId设置为链接表中的主键。我在做什么错了?
我有以下3种型号:
public class Client : IUser
{
[Key, ForeignKey(nameof(User)), DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public User User { get; set; }
public IList<ClientAdministration> ClientAdministrations { get; set;}
}
public class Administration
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public IList<ClientAdministration> ClientAdministrations { get; set;}
}
public class ClientAdministration
{
[key, Column(Order = 0)]
public int ClientId { get; set; }
public Client Client { get; set; }
[key, Column(Order = 1)]
public int AdministrationId { get; set; }
public Administration Administration { get; set; }
}
在我的Context.cs中,定义了以下关系:
modelBuilder.Entity<ClientAdministration>()
.HasKey(ca => new { ca.ClientId, ca.AdministrationId });
modelBuilder.Entity<ClientAdministration>()
.HasOne<Client>(ca => ca.Client)
.WithMany(c => c.ClientAdministrations)
.HasForeignKey(ca => ca.ClientId);
modelBuilder.Entity<ClientAdministration>()
.HasOne<Administration>(ca => ca.Administration)
.WithMany(a => a.ClientAdministrations)
.HasForeignKey(ca => ca.AdministrationId);