Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WCF服务奇怪的行为:实体框架在运行代码时引发异常,但在调试时工作正常_C#_Entity Framework_Wcf_Debugging - Fatal编程技术网

C# WCF服务奇怪的行为:实体框架在运行代码时引发异常,但在调试时工作正常

C# WCF服务奇怪的行为:实体框架在运行代码时引发异常,但在调试时工作正常,c#,entity-framework,wcf,debugging,C#,Entity Framework,Wcf,Debugging,我有一个WCF服务,即使用实体框架连接到数据库。我遇到了一种奇怪的行为——当我开始调试WCF服务并调用它的一个方法(操作契约)时,根据调试的方式,我得到了两种不同的场景。这意味着,当我只是调用该方法,而不进入代码时,我会得到一个异常,声明:“违反主键约束‘PK_TagIsUsedInPublication’。无法在对象‘dbo.TagIsUsedInPublication’中插入重复的键。重复的键值是(16,54)。”,当我在方法的开头放一个断点,然后逐步进入代码并逐行检查时,一切都正常。这怎么

我有一个WCF服务,即使用实体框架连接到数据库。我遇到了一种奇怪的行为——当我开始调试WCF服务并调用它的一个方法(操作契约)时,根据调试的方式,我得到了两种不同的场景。这意味着,当我只是调用该方法,而不进入代码时,我会得到一个异常,声明:“违反主键约束‘PK_TagIsUsedInPublication’。无法在对象‘dbo.TagIsUsedInPublication’中插入重复的键。重复的键值是(16,54)。”,当我在方法的开头放一个断点,然后逐步进入代码并逐行检查时,一切都正常。这怎么可能?我做错了什么

我的方法使用数据库中的两个实体——Publication和Tag。我还有一个桥接表,名为TagIsUsedInPublication。它有两个外键,一个指向发布表,另一个指向标记1。它有一个复合主键,由两列(外键)组成。当然,这意味着发布和标记具有多对多关系

以下是我的方法:

public static bool EditPublication(Interpretum.InterpretumService.SimplePublication publication)
{
    try
    {
        InterpretumDAL.InterpretumEntities interpretumEntities = new InterpretumDAL.InterpretumEntities();

        InterpretumDAL.Publication publicationDbContext =
            (from p in interpretumEntities.Publications
             where p.Id == publication.Id
             select p).SingleOrDefault();

        // This method just gets all the properties of my custom SimplePublication class and maps them to the Publication entity.
        publicationDbContext = publication.ToDbContext(publicationDbContext);

        if (publication.Tags.Count != 0)
        {
            publicationDbContext.Tags = Tag.RenderTagList(publication.Tags, publication.CreationUserId, interpretumEntities);
        }

        interpretumEntities.SaveChanges();
    }
    catch (Exception e)
    {
        // I added this throw line just to see what actually is causing the method fail. 
        throw e;
        return false;
    }

    return true;
}
RenderAglist方法是必需的,因为我的模式要求标记表的Name列具有uniqe值。因此,它正在检查是否已经存在具有提供的名称的标记。如果有,它将添加到标记列表中。如果不是,则创建一个新的,然后将其添加到列表中

下面是此方法的外观:

public static List<InterpretumDAL.Tag> RenderTagList(List<SimpleTag> simpleTags, int creationUserId, InterpretumDAL.InterpretumEntities interpretumEntities)
{
    List<InterpretumDAL.Tag> tags = new List<InterpretumDAL.Tag>();

    foreach (var simpleTag in simpleTags)
    {
        InterpretumDAL.Tag tag = interpretumEntities.Tags.FirstOrDefault(x => x.Name == simpleTag.Name);

        if (tag == null)
        {
            tag = new InterpretumDAL.Tag()
            {
                Name = simpleTag.Name,
                CreationUserId = creationUserId
            };
        }

        tags.Add(tag);
    }

    return tags;
}
publicstaticlistrendertaglist(列出simpleTags、int creationserid、interpretatumdal.interpretatumenties-interpretatumenties)
{
列表标签=新列表();
foreach(simpleTags中的var simpleTag)
{
expertumdal.Tag Tag=expertumenties.Tags.FirstOrDefault(x=>x.Name==simpleTag.Name);
if(标记==null)
{
tag=new expertumdal.tag()
{
Name=simpleTag.Name,
CreationUserId=CreationUserId
};
}
标签。添加(标签);
}
返回标签;
}
正如我在上面所写的,当我调用EditPublication时,会抛出一个异常。当然,我每次都用相同的值调用它,无论我调用它多少次,我总是得到这个异常。然而,当我一步一步地编写代码并逐行地检查方法时,一切都很好

我必须提到,我对实体框架相当陌生,所以很可能我做错了什么。问题是我看不出我做错了什么,只是因为这种不可预测的行为

编辑1:

堆栈跟踪:

at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
at System.Data.SqlClient.SqlConnection.OnError(SqlException异常,布尔breakConnection,Action`1 wrapCloseInAction)
位于System.Data.SqlClient.SqlInternalConnection.OneError(SqlException异常,布尔断开连接,操作'1 wrapCloseInAction)
位于System.Data.SqlClient.TdsParser.ThroweException和Warning(TdsParserStateObject StateObjectStateObj、布尔调用方连接锁、布尔异步关闭)
位于System.Data.SqlClient.TdsParser.TryRun(RunBehavior RunBehavior、SqlCommand cmdHandler、SqlDataReader dataStream、BulkCopySimpleResultSet bulkCopyHandler、TdsParserStateObject stateObj、Boolean和dataReady)
位于System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds、RunBehavior、String ResetOptions String)
位于System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior、RunBehavior RunBehavior、Boolean returnStream、Boolean async、Int32超时、任务和任务、Boolean asyncWrite、SqlDataReader ds)
位于System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior、RunBehavior RunBehavior、Boolean returnStream、String方法、TaskCompletionSource`1 completion、Int32超时、Task&Task、Boolean asyncWrite)
位于System.Data.SqlClient.SqlCommand.InternalExecuteOnQuery(TaskCompletionSource`1完成,字符串方法名,布尔sendToPipe,Int32超时,布尔异步写入)
位于System.Data.SqlClient.SqlCommand.ExecuteOnQuery()处
在System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.b_u0(DbCommand t,DbCommandInterceptionContext`1c)中
在System.Data.Entity.Infrastructure.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget目标,Func`3操作,TInterceptionContext拦截Context,操作`3执行,操作`3执行)
位于System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand命令,DbCommandInterceptionContext interceptionContext)
位于System.Data.Entity.Internal.InterceptableDbCommand.ExecuteOnQuery()处
在System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues,List`1 generatedValues)
位于System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()处

请发布堆栈跟踪。我认为您可能正在使用不同的数据源,具体取决于您运行的模式。可能类似于#if(DEBUG)使用数据源A#else使用数据源B。另一种更可能的解释是,代码中有竞争条件?这也许可以解释为什么一步一步的工作很好。我修复了bug,我不再有异常了,但是我仍然不明白为什么我会根据代码的运行方式得到不同的结果。不,我没有条件编译,就像你例子中的那个。顺便问一下,什么是比赛条件?