引用会创建双重条目

时间:2018-05-31 09:47:40

标签: c# entity-framework ef-code-first

在我的设置中,我有一个实体"约会"与相关实体"培训师"其中1个预约与1个培训师相关,但1个培训师可以分配到n个预约。培训师的创建按预期进行。创建约会后,培训师的数量增加了一倍。我假设Appointment和Trainer之间的引用是错误的。有什么想法吗?

顺便说一下,我跟着SQLiteCodeFirst进行了模型创建。 (在这里应该没有效果,我假设)。

培训师:

[Table("Trainer")]

public class Trainer : IEntity
{
    [Autoincrement]
    public int Id { get; set; }
    public String Name { get; set; } = "";
}

预约:

[Table("Appointment")]
public class Appointment 
{
    [Autoincrement]
    public int Id { get; set; }
    public virtual Trainer Trainer { get; set; } 
}

我的虚拟价值创造:

 context.Set<Trainer>().Add(new Trainer {Name = "Max Mustermann"});
 context.Set<Trainer>().Add(new Trainer {Name = "Fritze Bollmann"});
 context.Set<Trainer>().Add(new Trainer {Name = "Andi Mauer"});
 context.SaveChanges();

 List<Trainer> trainers = Trainers(); //here the count of trainers is correct
 //do this 100 times:
 Random gen = new Random();
 int t = gen.Next(trainers.Count);
 appointment.Trainer = trainers[t];
 context.SaveChanges();

 // here the count of trainers is wrong

 public static List<Trainer> Trainers()
 {
      using (var context = new PDEDbContext(DbName))
      {
          return context.Set<Trainer>().ToList();
      }
 }

0 个答案:

没有答案