无法制作组合键?我要去哪里错了?

时间:2019-11-11 14:39:01

标签: c# entity-framework

我正在尝试建立多对多关系。一个客户需要能够拥有许多管理人员,而一个管理部门应该能够拥有许多客户。我的问题:在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);

1 个答案:

答案 0 :(得分:0)

根据this,Key属性定义了主键。

在链接表中,两个键都是外键,而不是主键。