我有同样的问题。我为解决它所做的工作是创建另一个专门用于处理连接的派生 DbContext。IE:
public class JoinContext : DbContext
{
internal JoinContext() : base("name=SampleConnectionString")
{
PreventErrorIfDatabaseSchemaChanges();
// Get the ObjectContext related to this DbContext
var objectContext = (this as IObjectContextAdapter).ObjectContext;
}
public DbSet<StudentImage> StudentImages { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<StudentImage>()
.ToTable("StudentImages");
.HasKey(joinTable => new { joinTable.StudentId, joinTable.ImageId });
base.OnModelCreating(modelBuilder);
}
private static void PreventErrorIfDatabaseSchemaChanges()
{
Database.SetInitializer<JoinContext>(null);
}
}
我将其他应用程序上下文与 Student/Image 多对多连接映射保持原样。不要忘记为连接表指定复合键(参考上面的 HasKey 方法),否则 EF 会在数据库初始化时发生炸弹。
获得特殊连接上下文后,使用存储库访问此上下文并从映射连接表中获取或设置所需字段:
public class StudentRepository
{
public int GetImageSortOrder(int studentId, int imageId)
{
var joinContext = new JoinContext();
var joinTuple = joinContext.StudentImages.Find(studentId, imageId);
return joinTuple.SortOrder;
}
}
希望这可以帮助!