我正在使用带有剃刀语法和实体框架6的asp.net mvc 5开发内部网应用程序,但是当我运行应用程序时,会出现EntitySqlException
。
当我查看错误消息时,我有这个:
实体集或功能导入' COVENANTS_RT'没有在实体容器中定义' Model1'。
这是我的Model1 DbContext
:
public partial class Model1 : DbContext
{
public Model1() : base("name=Model1")
{
}
public virtual DbSet<covenants> covenants { get; set; }
public virtual DbSet<covenants_detalhes> covenants_detalhes { get; set; }
public virtual DbSet<COVENANTS_RT> COVENANTS_RT { get; set; }
public virtual DbSet<RT> RT { get; set; }
public virtual DbSet<VW_USUARIOS> VW_USUARIOS { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
...
modelBuilder.Entity<RT>()
.Property(e => e.nome_operacao)
.IsUnicode(false);
modelBuilder.Entity<RT>()
.HasMany(e => e.COVENANTS_RT)
.WithRequired(e => e.RT)
.HasForeignKey(e => e.FK_COD_RT);
这是我的模型类COVENANTS_RT
:
[Table("COVENANTS_RT")]
public partial class COVENANTS_RT
{
[Key]
public int CODIGO_COVENANT_PK { get; set; }
[Column(TypeName = "ntext")]
public string texto_covenant { get; set; }
[StringLength(255)]
public string situacao { get; set; }
[Column(TypeName = "ntext")]
public string OBS { get; set; }
public int FK_COD_RT { get; set; }
public virtual RT RT { get; set; }
}
班级RT
:
[Table("RT")]
public partial class RT
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public RT()
{
COVENANTS_RT = new HashSet<COVENANTS_RT>();
}
[Key]
public int PK_CODIGO_RT { get; set; }
...
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<COVENANTS_RT> COVENANTS_RT { get; set; }
}
剃刀页面中出现错误的代码:
@model site_covenants.Models.RT
@{
Layout = null;
}
...
@foreach (var Item in Model.COVENANTS_RT )
那么,我要做些什么来解决这个问题呢?
答案 0 :(得分:0)
这里的代码行public partial class Model1 : DbContext
实际上是你的DbContext而不是模型。相应地命名对象总是更好。
例如:public partial class ApplicationDbContext : DbContext
Model1
。{/ p>
为了使用流畅的api,您需要覆盖OnModelCreating
方法:
public partial class ApplicationDbContext : DbContext
{
public virtual DbSet<covenants> covenants { get; set; }
public virtual DbSet<covenants_detalhes> covenants_detalhes { get; set; }
public virtual DbSet<COVENANTS_RT> COVENANTS_RT { get; set; }
public virtual DbSet<RT> RT { get; set; }
public virtual DbSet<VW_USUARIOS> VW_USUARIOS { get; set; }
public ApplicationDbContext()
: base("name=Model1")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<RT>()
.Property(e => e.nome_operacao)
.IsUnicode(false);
modelBuilder.Entity<RT>()
.HasMany(e => e.COVENANTS_RT)
.WithRequired(e => e.RT)
.HasForeignKey(e => e.FK_COD_RT);
}
}