我尝试使用此模型在User和TeamMember之间建立0-1关系
public class User
{
[Key]
public Guid Id { get; set; }
public Guid? TeamMemberId { get; set; }
public virtual TeamMember TeamMember { get; set; }
}
public partial class TeamMember
{
[Key]
[Column(Order = 0)]
public Guid TeamId { get; set; }
[Key]
[Column(Order = 1)]
public Guid UserId { get; set; }
public virtual MSUCTeam Team { get; set; }
public virtual User User { get; set; }
}
public class Team
{
[Key]
public Guid Id { get; set; }
public virtual ICollection<TeamMember> TeamMembers { get; set; }
}
要告诉EF关于这种关系的所有信息,我使用了如下的流利API
modelBuilder.Entity<Team>()
.HasMany(e => e.TeamMembers)
.WithRequired(e => e.Team)
.HasForeignKey(e => e.TeamId).WillCascadeOnDelete();
modelBuilder.Entity<User>()
.HasOptional(e => e.TeamMember)
.WithRequired(e => e.User);
表格本身是在上下文中定义的
public virtual DbSet<Team> Teams { get; set; }
public virtual DbSet<TeamMembers> TeamMembers { get; set; }
这会在数据库中生成所需的表,但TeamMembers表有3列:
1)TeamId(Guid,非可空):PK和FK链接到Team.Id. 2)UserId(Guid,non nullable):PK。 3)User_Id(Guid,不可为空):FK链接到User.Id
如何将UserId列作为链接到User表的PK和FK?在没有UserId和TeamId的情况下,我们不会成为TeamMember的参赛者,但我必须告诉EF错误的我想要它做什么。
答案 0 :(得分:0)
我真的无法测试这个,但尝试设置外键注释
public partial class TeamMember
{
[Key]
[Column(Order = 0)]
public Guid TeamId { get; set; }
[Key]
[Column(Order = 1)]
public Guid UserId { get; set; }
[ForeignKey("TeamId")]
public virtual MSUCTeam Team { get; set; }
[ForeignKey("UserId")]
public virtual User User { get; set; }
}
答案 1 :(得分:0)
使用它:
public class User
{
[Key]
public Guid Id { get; set; }
public virtual TeamMember TeamMember { get; set; }
}
public partial class TeamMember
{
[Key, ForeignKey("User")]
public Guid Id{ get; set; }
public virtual User User { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TeamMember>()
.HasRequired(p => p.User)
.WithOptional(p => p.TeamMember);
}
有关拆分表的详细信息,请查看此link;