【问题标题】:EF code first, child holds a list of parent objectsEF代码优先,child持有父对象列表
【发布时间】:2017-07-10 14:19:27
【问题描述】:

我在 EF 代码方面遇到了一个令人讨厌的问题,我需要一些帮助。我有一个Student,它继承自Person。学生可以有像Worker 这样的朋友,它们也继承自人。

class Person
{
    public int Id { get; set; }
    //...
}

class Student : Person
{
    public virtual List<Person> Friends { get; set; }
    //...
}

class Worker : Person
{
    //there are other classes like this one
}

这是我尝试将实体写入我的 sqlite DB 时遇到的异常:

元数据集合中不存在身份为“PersonSelf”的成员。

如果我将列表更改为 Worker,它可以正常工作,但不能与 Person 一起使用。 我可以改变什么来解决这个问题?感谢您的帮助。

【问题讨论】:

  • 在表上使用触发器时,通过谷歌搜索会发现类似的问题。你有触发器吗?
  • 我搜索了很多,确实发现了一些类似的问题,但不幸的是不完全是多态性的问题。据我所知,我没有使用触发器......
  • 您能否提供有关您的表如何实现层次结构的更多详细信息? TPH 还是 TPC?既然 Friends 是 n:m 关系,你有表吗?

标签: c# sqlite ef-code-first polymorphism


【解决方案1】:

如果你已经很好地定义了你的模型和数据库上下文,我认为你应该没有任何问题。我在 github 上创建了一个小型 repo 来测试你的模型。链接在这里 github repo 我的模型非常简单:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

}
public class Student : Person
{
    public Student()
    {
        Friends=new List<Person>();
    }
    public virtual List<Person> Friends { get; set; }
    public int StudentAge { get; set; }
}
public class Worker : Person
{
    public decimal WorkerSalary { get; set; }
}

我正在使用 DotNet Core,我能够创建数据库并插入数据。

请检查 repo 并告诉我它是否适合您。

【讨论】:

    【解决方案2】:

    感谢您的提示。要解决这个问题,需要告诉 EF 在 DB 中创建映射表。原因是因为这是一个“多对多”问题。

    请考虑我的另一个post

        public class ModelConfiguration
        {
            private static void ConfigureGridDataCollectionEntity(DbModelBuilder modelBuilder)
            {
                // Student
                modelBuilder.Entity<Student>()
                    .HasMany(p => p.Friends)
                    .WithMany()
                    .Map(cs =>
                    {
                        cs.MapLeftKey("StudentId");
                        cs.MapRightKey("FriendsId");
                        cs.ToTable("StudentFriend");
                    });
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多