在DbContext中无法访问创建的实体OnModelCreating

时间:2019-09-25 17:10:52

标签: c# entity-framework entity-framework-6

我有多对多关系映射,并且映射表有一个附加字段。我创建了ApplicationDbContext,如下所示:

        public virtual DbSet<Country> Countries { get; set; }
        public virtual DbSet<Region> Regions { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<CountryRegionMapping>()
                .HasKey(um => um.CountryRegionMappingId)
                .ToTable("CountryRegionMapping");

            modelBuilder.Entity<CountryRegionMapping>()
                .HasRequired(um => um.Region).WithMany(g => g.CountryMappings)
                .HasForeignKey(um => um.RegionId);

            modelBuilder.Entity<CountryRegionMapping>()
                .HasRequired(um => um.Country).WithMany(g => g.RegionMappings)
                .HasForeignKey(um => um.CountryId);

            base.OnModelCreating(modelBuilder);
        }

我指的是this link,以创建在映射表中具有一个额外字段的多对多关系。

实体类是:

    public class Country
    {
        public int Id { get; set; }
        public string SystemOneName { get; set; }
        public string SystemTwoName { get; set; }
        public virtual ICollection<CountryRegionMapping> RegionMappings { get; set; }
    }

    public class Region
    {
        public int Id { get; set; }
        public string SystemOneName { get; set; }
        public string SystemTwoName { get; set; }
        public virtual ICollection<CountryRegionMapping> CountryMappings { get; set; }
    }

    public class CountryRegionMapping
    {
        public int CountryRegionMappingId { get; set; }
        public int CountryId { get; set; }
        public virtual Country Country { get; set; }
        public int RegionId { get; set; }
        public virtual Region Region { get; set; }
        public bool CheckField { get; set; }
    }

当我尝试访问Country或Region表时,我可以使用dbcontext.Regions通过下面的代码简单地访问它

ApplicationDbContext db = new ApplicationDbContext();
db.Regions.SingleOrDefault(r => r.Id == Id);

但是当我尝试访问“ CountryRegionMapping”实体时,无法通过db.CountryRegionMapping之类的代码进行访问

为什么在Db上下文中不可用。如何在多对多关系中间访问该实体。

1 个答案:

答案 0 :(得分:0)

如果您想直接访问中间映射实体,请在上下文中将它们添加为DbSet以及其他实体:

public virtual DbSet<CountryRegionMapping> CountryRegionMappings { get; set; }

public virtual DbSet<Country> Countries { get; set; }
public virtual DbSet<Region> Regions { get; set; }

然后,您可以像访问CountriesRegions一样访问它们:

ApplicationDbContext db = new ApplicationDbContext();
db.CountryRegionMappings//.SingleOrDefault, etc.