gpt4 book ai didi

c# - EF TPT 生成重复的外键

转载 作者:行者123 更新时间:2023-11-30 17:44:38 24 4
gpt4 key购买 nike

我正在编写一个使用继承的应用程序,我试图将其映射到具有 TPT 结构的 SQL Server 数据库。

但是,出于某种原因,EF 在父类(super class)表和子类表中生成了重复的外键。

我有这些类(class):

public abstract class Answer
{
public int AnswerId { get; set; }
[Required]
[MaxLength(250, ErrorMessage = "The answer cannot contain more than 250 characters")]
public String Text { get; set; }
[Required]
[MaxLength(1500, ErrorMessage = "The description cannot contain more than 1500 characters")]
public String Description { get; set; }

public User User { get; set; }
}

public class AgendaAnswer : Answer
{
[Required]
public AgendaModule AgendaModule { get; set; }
}

public class SolutionAnswer : Answer
{
[Required]
public SolutionModule SolutionModule { get; set; }
}

public abstract class Module
{
// for some reason EF doesn't recognize this as primary key
public int ModuleId { get; set; }
[Required]
public String Question { get; set; }
public String Description { get; set; }
[Required]
public DateTime StartTime { get; set; }
[Required]
public DateTime EndTime { get; set; }

public virtual IList<Tag> Tags { get; set; }
}

public class AgendaModule : Module
{
public IList<AgendaAnswer> AgendaAnswers { get; set; }
}

public class SolutionModule : Module
{
public IList<SolutionAnswer> SolutionAnswers { get; set; }
}

public class User
{
public int UserId { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public int Zip { get; set; }
public bool Active { get; set; }

public virtual IList<AgendaAnswer> AgendaAnswers { get; set; }
public virtual IList<SolutionAnswer> SolutionAnswers { get; set; }
}

这是我的 DbContext 类的内容:

public DbSet<AgendaModule> AgendaModules { get; set; }
public DbSet<SolutionModule> SolutionModules { get; set; }
public DbSet<AgendaAnswer> AgendaAnswers { get; set; }
public DbSet<SolutionAnswer> SolutionAnswers { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

modelBuilder.Entity<Module>().HasKey(m => m.ModuleId);
modelBuilder.Entity<Answer>().HasKey(a => a.AnswerId);

modelBuilder.Entity<AgendaAnswer>().Map(m =>
{
m.ToTable("AgendaAnswers");
});

modelBuilder.Entity<SolutionAnswer>().Map(m =>
{
m.ToTable("SolutionAnswers");
});
}

当我运行我的应用程序时,EF 按照我想要的方式创建表 (TPT),但它会为每个表中的用户复制外键(参见图片)。

enter image description here

提前致谢

最佳答案

如我在上面的评论中所述,解决方案是从 User 类中删除 AgendaAnswersSolutionAnswers 属性。

如果您想将这些集合保留在 User 类中,您可能必须从 中删除 UserUserId 属性>Answer 类,而是在 AgendaAnswerSolutionAnswer 类中复制它们。参见 this SO question获取更多信息。

关于c# - EF TPT 生成重复的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29326973/

24 4 0
文章推荐: javascript - 未捕获的类型错误 : Object # has no method 'Jcrop'