gpt4 book ai didi

entity-framework - Code First - 两个外键作为主键,无法添加迁移

转载 作者:行者123 更新时间:2023-12-02 17:42:58 25 4
gpt4 key购买 nike

我的用户表:

public class User
{
[Key]
public int UserId { get; set; }

public virtual ICollection<PollVote> PollVotes { get; set; }
}

我的投票表:

public class Poll
{
[Key]
public int PollId { get; set; }

public virtual ICollection<PollVote> PollVotes { get; set; }
}

我的投票表

public class PollVote
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int VoteId { get; set; }

[Key]
public int PollId { get; set; }

[Key]
public int UserId { get; set; }

public DateTime TimeVoted { get; set; }
public int Answer { get; set; }

public virtual Poll Poll { get; set; }
public virtual User User { get; set; }
}

我的配置:

//User config:
this.HasMany(x => x.PollVotes)
.WithRequired()
.HasForeignKey(x => x.UserId)
.WillCascadeOnDelete(false);

//Poll Config
this.HasMany(x => x.PollVotes)
.WithRequired()
.HasForeignKey(x => x.PollId)
.WillCascadeOnDelete(false);

//PollVote Config
this.HasKey(x => x.UserId)
.HasRequired(x => x.User)
.WithMany()
.HasForeignKey(x => x.UserId);
this.HasKey(x => x.PollId)
.HasRequired(x => x.Poll)
.WithMany()
.HasForeignKey(x => x.PollId);

关系是:一次投票可以有很多票,但是一个用户每次投票只能投一票。

当我尝试在 PM-Console 中 Add-Migration 时出现此错误

\tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'PollVote_Poll_Source' in relationship 'PollVote_Poll'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'. \tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'Poll_PollVotes_Target' in relationship 'Poll_PollVotes'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'.

有什么建议吗?

最佳答案

您可以通过添加 [Column] 来指定复合键属性到数据注释...

    [Key, Column(Order = 1)]
public int PollId { get; set; }

[Key, Column(Order = 2)]
public int UserId { get; set; }

...或者通过 Fluent API 使用匿名对象:

this.HasKey(x => new { x.UserId, x.PollId });

this.HasRequired(x => x.User)
.WithMany(u => u.PollVotes)
.HasForeignKey(x => x.UserId);

this.HasRequired(x => x.Poll)
.WithMany(p => p.PollVotes)
.HasForeignKey(x => x.PollId);

不要忘记 WithMany 中反向导航属性的 lambda 表达式,如上图,去掉UserConfig中多余的配置和 PollConfig .

关于entity-framework - Code First - 两个外键作为主键,无法添加迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18166763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com