0

エンティティ フレームワークの使用に問題が発生しています。これは、DB コンテキストを正しく使用していないことが原因であると考えられます。

ときどき、「モデルの作成中はコンテキストを使用できません」というエラー メッセージがログに表示されます。

エラーは常に発生するとは限らず、アプリケーションの新規ロード時、またはプロジェクトをコンパイルしてコンパイル中にブラウザー タブを更新した場合に発生するようです。

以下の関数は、エラーが発生しており、マスター ページから呼び出される関数です。

public static class UserFunctions
{
    private static peopleSwimmingContext _db = new peopleSwimming.Models.peopleSwimmingContext();

    public static String GetUserRole(Int32 UserID) {

        String returnedRole = String.Empty;

        var foundUser = _db.Users.Where(w => w.UserId == UserID).FirstOrDefault();
        if (foundUser != null)
        {
            returnedRole = foundUser.Role.Name;
        }
        return returnedRole;
    }
}

どんなヒントでも大歓迎です!

ああ、ここに私のinnerstackトレースがあります:

内部スタック トレース:

System.Data.Entity.Internal.LazyInternalContext.InitializeContext() で System.Data.Entity.Internal.InternalContext.Initialize() で System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) で System.Data.Entity .Internal.Linq.InternalSet 1.get_InternalContext 1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet() System.Data.Entity.Infrastructure.DbQuery で1.System.Linq.IQueryable.get_Provider() at System.Linq.Queryable.Where[TSource](IQueryablec:\svn\peopleSwim\peopleSwimming\Logic\UserFunctions.cs:line 18 at peopleSwimming._Home.Page_Load(Object sender, EventArgs e) の peopleSwimming.Logic.UserFunctions.GetUserRole(Int32 UserID) ) System.Web.UI.Control.OnLoad(EventArgs e) の System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) の c:\svn\peopleSwim\peopleSwimming\Home.aspx.cs:line 25 でSystem.Web.UI.Control.LoadRecursive() で System.Web.UI.Page.ProcessRequestMain (ブール値 includeStagesBeforeAsyncPoint、ブール値 includeStagesAfterAsyncPoint)

4

1 に答える 1

3

データ コンテキストを初期化して破棄するステートメントでコードをラップして、using必要になる直前から直後まで使用できるようにしてください。これにより、確実に廃棄されます。

また、メソッドは必要ありません。Whereただ使用できますFirstOrDefault

public static class UserFunctions
{
    public static String GetUserRole(Int32 UserID) 
    {
        using (peopleSwimmingContext _db = new peopleSwimming.Models.peopleSwimmingContext())
        {
            String returnedRole = String.Empty;

            var foundUser = _db.Users.FirstOrDefault(w => w.UserId == UserID);

            if (foundUser != null)
            {
                returnedRole = foundUser.Role.Name;
            }

            return returnedRole;
        }
    }
}
于 2013-04-22T08:41:14.237 に答える