EF Core和封装的集合

时间:2018-08-27 19:28:09

标签: c# entity-framework-core

我正在尝试遵循以下建议:https://ardalis.com/encapsulated-collections-in-entity-framework-core

我有一堂课,看起来像这样:

public class Person
{
    public Guid Id { get; private set; }
    public string Name { get; private set; }
    private readonly List<PersonSport> _entries = new List<PersonSport>();
    public IEnumerable<PersonSport> Entries => _entries.AsReadOnly();

    public void AddEntry(PersonSport entry)
    {
        _entries.Add(entry);
    }
}

和dbcontext,如下所示:

public class PersonSportContext : DbContext
{
    public DbSet<Person> Person { get; set; }
    public DbSet<Sport> Sport{ get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<PersonSport>().HasKey(sc => new { sc.PersonId, sc.SportId });
        modelBuilder.Entity<Sport>()
       .ToTable("Sport")
       .HasDiscriminator<string>("SportType")
       .HasValue<Football>("Football")
       .HasValue<Running>("Running");

        modelBuilder.Entity<PersonSport>()
            .HasOne<Person>(sc => sc.Person)
            .WithMany(s => s.PersonSport)
            .HasForeignKey(sc => sc.PersonId);


        modelBuilder.Entity<PersonSport>()
            .HasOne<Sport>(sc => sc.Sport)
            .WithMany(s => s.PersonSport)
            .HasForeignKey(sc => sc.SportId);

        var navigation = modelBuilder.Entity<Person>().Metadata.FindNavigation(nameof(ConsoleApp1.Person.PersonSport));
        navigation.SetPropertyAccessMode(PropertyAccessMode.Field);
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=PersonSport;Trusted_Connection=True;MultipleActiveResultSets=true");
    }

我看到一个编译错误:

  

“ DbSet不包含条目的定义”。

我已突出显示了使用注释错误的行(由于编译错误,“条目”用红色下划线显示)。我花了几个小时在谷歌上搜索,却一无所获。我在做什么错了?

更新 cwharris的回答有助于解决编译错误。现在运行。我已经创建了一个控制台应用程序来对其进行测试:

static void Main(string[] args)
        {
            PersonSportContext personSportContext = new PersonSportContext();
            var person = personSportContext.Person.Include(t => t.PersonSport).FirstOrDefault(); 
            var sport = personSportContext.Sport.Include(t => t.PersonSport).FirstOrDefault();
            Console.WriteLine("Finished");
        }

请查看以下屏幕截图:

enter image description here

请注意,Person.PersonSport.Sport为null。现在看下面的内容(当我在以下行中停止调试器时):

enter image description here

请注意,Person.PersonSport.Sport不再为null。

这是为什么?填充Person变量时,如何确保Person.PersonSport.Sport被填充?

1 个答案:

答案 0 :(得分:4)

看起来nameof(Person.Entries)旨在引用Person类,但实际上由于缺少Person类的PersonSportContext属性名称空间。尝试在Person运算符中添加nameof类名称空间。

nameof(Person.Entries)

应该成为

nameof(MyNamespaceWherePersonClassResides.Person.Entries)