我有Issue
实体,其中有2个字段,分别为FK
至User
实体,如下所示。尽管我已正确配置属性以防止创建额外的Xxx_Id
字段而不是PropertyNameId
,但是在表中除了Xxx_Id
字段之外还创建了一个PropertyNameId
字段。在此示例中,在User_Id
和Issue
字段之外的AssigneeId
表中创建了ReporterId
字段。这里有什么错误吗? HashSet
实体中的User
是否导致此额外的User_Id
字段?
问题:
public class Issue : BaseEntity
{
[Key]
public int Id { get; set; }
//Foreign key for Reporter (User entity)
public short ReporterId { get; set; }
//Foreign key for Assignee (User entity)
public short AssigneeId { get; set; }
[ForeignKey("ReporterId")]
public virtual User Reporter { get; set; }
[ForeignKey("AssigneeId")]
public virtual User Assignee { get; set; }
}
用户:
public class User : BaseEntity
{
[Key]
public short Id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
//code omitted for brevity
public User()
{
Issues = new HashSet<Issue>();
//code omitted for brevity
}
public virtual ICollection<Issue> Issues { get; set; }
//code omitted for brevity
}
以下是迁移文件中的相关行:
CreateTable(
"Issue",
c => new
{
Id = c.Int(nullable: false, identity: true),
ReporterId = c.Short(nullable: false),
AssigneeId = c.Short(nullable: false),
User_Id = c.Short() //???
})
.PrimaryKey(t => t.Id)
.ForeignKey("com.User", t => t.User_Id) //???
.ForeignKey("com.User", t => t.AssigneeId)
.ForeignKey("com.User", t => t.ReporterId)
.Index(t => t.ReporterId)
.Index(t => t.AssigneeId)
.Index(t => t.User_Id); //???
答案 0 :(得分:1)
当您尝试创建多个相同类型的ForeignKey
时,
您的模型类设置应如下:
public class User : BaseEntity
{
public User()
{
ReporterIssues = new HashSet<Issue>();
AssigneeIssues = new HashSet<Issue>();
}
[Key]
public short Id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
// Navigation properties
public virtual ICollection<Issue> ReporterIssues { get; set; }
public virtual ICollection<Issue> AssigneeIssues { get; set; }
}
public class Issue : BaseEntity
{
[Key]
public int Id { get; set; }
public short ReporterId { get; set; }
public short AssigneeId { get; set; }
// Navigation properties
public virtual User Reporter { get; set; }
public virtual User Assignee { get; set; }
}
然后在OnModelCreating
配置中如下:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>().HasMany(u => u.AssigneeIssues)
.WithRequired(i => i.Assignee).HasForeignKey(a => a.AssigneeId)
.WillCascadeOnDelete(false); // <-- cascade delete must be false
modelBuilder.Entity<User>().HasMany(u => u.ReporterIssues)
.WithRequired(i => i.Reporter).HasForeignKey(a => a.ReporterId)
.WillCascadeOnDelete(false); // <-- cascade delete must be false
}