【发布时间】:2014-12-08 17:34:02
【问题描述】:
这是我的模型
public class Game
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string GameName { get; set; }
public virtual ICollection<GameImages> GameImage { get; set; }
}
public class GameImages
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[DataType(DataType.ImageUrl)]
public string GameImageUrl { get; set; }
public int Game_Id { get; set; }
[ForeignKey("Game_Id")]
public virtual Game games { get; set; }
}
public class GameDbContext:DbContext
{
public GameDbContext():base("name=DefaultConnection") { }
public DbSet<Game> Games { get; set; }
public DbSet<GameImages> Images { get; set; }
}
我有两个使用 Entity Framework 进行读/写操作的控制器。我使用 EF 添加了另一个具有读/写操作的 Web api 控制器。尝试访问 GET api 时出现以下错误
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The context cannot be used while the model is being created.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext() at System.Data.Entity.Internal.InternalContext.Initialize() at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet`1.ToString() at System.Data.Entity.Infrastructure.DbQuery`1.ToString() at System.Convert.ToString(Object value, IFormatProvider provider) at System.Web.Http.Tracing.FormattingUtilities.ValueToString(Object value, CultureInfo cultureInfo) at System.Web.Http.Tracing.Tracers.HttpActionDescriptorTracer.<ExecuteAsync>b__2(TraceRecord tr, Object value) at System.Web.Http.Tracing.ITraceWriterExtensions.<>c__DisplayClass1b`1.<>c__DisplayClass1f.<TraceBeginEndAsync>b__13(TraceRecord traceRecord) at System.Web.Http.Tracing.SystemDiagnosticsTraceWriter.Trace(HttpRequestMessage request, String category, TraceLevel level, Action`1 traceAction) at System.Web.Http.Tracing.ITraceWriterExtensions.<>c__DisplayClass1b`1.<TraceBeginEndAsync>b__12(TResult result) at System.Threading.Tasks.TaskHelpersExtensions.<>c__DisplayClass3b`2.<Then>b__3a(Task`1 t) at System.Threading.Tasks.TaskHelpersExtensions.ThenImpl[TTask,TOuterResult](TTask task, Func`2 continuation, CancellationToken cancellationToken, Boolean runSynchronously)
</StackTrace>
</Error>
需要帮助吗?
【问题讨论】:
-
1) 什么代码抛出了这个异常? 2) 采取了哪些措施导致此错误?
-
只需导航到该获取 api
-
您的上下文没有数据库初始化程序,这是否意味着您首先使用数据库?
-
是的,我首先使用代码
标签: c# entity-framework asp.net-mvc-4 asp.net-web-api