【发布时间】:2019-09-26 01:18:30
【问题描述】:
我有一个多对多关系映射,并且映射表有一个附加字段。我创建了 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 上下文中不可用。如何在多对多关系中访问此实体。
【问题讨论】:
标签: c# entity-framework entity-framework-6