我现在一直在努力将一个在模型中创建的相当大的EntityFramework数据库转换为codefirst。我有一个似乎无法解决的问题。我在调用堆栈上使用以下过程将对象引用设置为未设置为对象的实例。
ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure
ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntities
简化帖子我创建了一个测试项目,将问题简化为最简单的形式。
我有3个班级
c,它有一个可选的b和一个
的集合public class a
{
public int Id { get; set; }
[Required]
public string name { get; set; }
public virtual b b { get; set; }
[ForeignKey("b")]
public int? b_Id { get; set; }
public virtual c c { get; set; }
[ForeignKey("c")]
public int? c_Id { get; set; }
}
public class b
{
public int Id { get; set; }
public string name { get; set; }
public virtual ICollection<a> a_s { get; set; }
public virtual ICollection<c> c_s { get; set; }
}
public class c
{
public int Id { get; set; }
public virtual b b { get; set; }
[ForeignKey("b")]
public int? b_Id { get; set; }
public virtual ICollection<a> a_s { get; set; }
}
public class MyContext : DbContext
{
public DbSet<a> a { get; set; }
public DbSet<b> b { get; set; }
public DbSet<c> c { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<a>()
.HasOptional(m => m.b)
.WithMany(m => m.a_s);
modelBuilder.Entity<b>()
.HasMany(m => m.c_s)
.WithRequired(m => m.b);
modelBuilder.Entity<c>()
.HasMany(m => m.a_s)
.WithOptional(m => m.c);
base.OnModelCreating(modelBuilder);
}
}
当我在db.a select o中执行代码var a = from o时,我得到上述错误。绝对没有关于什么是hapenning的信息,所以我真的不知道在哪里转。任何人都可以帮我解决这个问题,因为我真的想摆脱Model First。
namespace MvcApplication2.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var db = new MyContext();
var a = from o in db.a select o;
return View();
}
}
}
答案 0 :(得分:3)
流畅的配置和数据注释的混合导致了这个问题。 EF团队应该处理此异常并给出有意义的错误消息。
删除数据注释并使用如下的流畅配置
public class a
{
public int Id { get; set; }
[Required]
public string name { get; set; }
public virtual b b { get; set; }
public int? b_Id { get; set; }
public virtual c c { get; set; }
public int? c_Id { get; set; }
}
public class b
{
public int Id { get; set; }
public string name { get; set; }
public virtual ICollection<a> a_s { get; set; }
public virtual ICollection<c> c_s { get; set; }
}
public class c
{
public int Id { get; set; }
public virtual b b { get; set; }
public int? b_Id { get; set; }
public virtual ICollection<a> a_s { get; set; }
}
public class NreContext : DbContext
{
public DbSet<a> a { get; set; }
public DbSet<b> b { get; set; }
public DbSet<c> c { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<a>()
.HasOptional(m => m.b)
.WithMany(m => m.a_s)
.HasForeignKey(m => m.b_Id);
modelBuilder.Entity<a>()
.HasOptional(m => m.c)
.WithMany(m => m.a_s)
.HasForeignKey(m => m.c_Id);
modelBuilder.Entity<c>()
.HasOptional(m => m.b)
.WithMany(m => m.c_s)
.HasForeignKey(m => m.b_Id);
base.OnModelCreating(modelBuilder);
}
}
答案 1 :(得分:1)
尝试将'a'放入本地内存:
var a = from o in db.a.ToList() select o;