Azure App Service(Mobile)上的db上下文失败

杰蒂姆

我有一个在Azure App Service-Mobile上运行的控制器。跟踪显示以下代码可以正常运行,直到db.SaveChanges()失败为止

var telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
telemetry.TrackTrace("Create User");
using (BCMobileAppContext db = new BCMobileAppContext())
{
     string Username_NoSpaces = username.Username.Replace(" ", "");
     var user = db.Users.FirstOrDefault(u => u.Username_NoSpaces == Username_NoSpaces || u.MicrosoftToken == this.User.Identity.Name);
     telemetry.TrackTrace("1");
     if (user == null && !Username_NoSpaces.Contains(","))
     {
          telemetry.TrackTrace("2");
           DateTime now = DateTime.UtcNow;
           telemetry.TrackTrace("3");
           string username_noSpaces = username.Username.Replace(" ", "");
           DataObjects.User userItem = new DataObjects.User() { Created = now, UserId = this.User.Identity.Name, MicrosoftToken = this.User.Identity.Name, Username_NoSpaces = username_noSpaces, Update = now, Username = username.Username, Gold = 1, Level = 1, Title = "Sir", InGameCrest = "", ReceiveNotifications = true };
           telemetry.TrackTrace("4");
           UserDTO returnObject1 = new UserDTO() { Created = userItem.Created, isCreated = true, MicrosoftId = userItem.MicrosoftToken, Username = userItem.Username };
            telemetry.TrackTrace("5");
            db.Users.Add(userItem);
            telemetry.TrackTrace("6");
            db.SaveChanges();         //Trace and code fails
            telemetry.TrackTrace("7");
            UserDTO returnObject = new UserDTO() { Created = userItem.Created, isCreated = true, MicrosoftId = userItem.MicrosoftToken, Username = userItem.Username };
            telemetry.TrackTrace("8");
            return Ok(returnObject);
       }
}

来自appservice诊断的stacktrace(不幸的是,我不理解)给出:

2016-04-07T17:29:19  PID[5008] Error       Operation=ReflectedHttpActionDescriptor.ExecuteAsync, Exception=System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at BCMobileAppService.Controllers.Test2Controller.Post(UserDTO username) in C:\Users\johann\Desktop\BCMobileApp_Runtime\BCMobileAppService\Controllers\TestController.cs:line 78
   at lambda_method(Closure , Object , Object[] )
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary 2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18 1.MoveNext()
2016-04-07T17:29:19  PID[5008] Error       Operation=ApiControllerActionInvoker.InvokeActionAsync, Exception=System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at BCMobileAppService.Controllers.Test2Controller.Post(UserDTO username) in C:\Users\johann\Desktop\BCMobileApp_Runtime\BCMobileAppService\Controllers\TestController.cs:line 78
   at lambda_method(Closure , Object , Object[] )
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary 2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18 1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18 1.MoveNext()
2016-04-07T17:29:19  PID[5008] Error       Operation=Test2Controller.ExecuteAsync, Exception=System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at BCMobileAppService.Controllers.Test2Controller.Post(UserDTO username) in C:\Users\johann\Desktop\BCMobileApp_Runtime\BCMobileAppService\Controllers\TestController.cs:line 78
   at lambda_method(Closure , Object , Object[] )
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.< >c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary 2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18 1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18 1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Tracing.Tracers.HttpControllerTracer.<ExecuteAsyncCore>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__18 1.MoveNext()

更新

因此,我将尝试使用this,它将给出更详细的错误消息:

catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
    foreach (var validationError in validationErrors.ValidationErrors)
    {
        Trace.TraceInformation("Property: {0} Error: {1}", 
                                validationError.PropertyName, 
                                validationError.ErrorMessage);
    }
}
}

我将通过所有的设置,以确保一个必须不能场nullnull因为按照这个答案的计算器

测试以上

例外隐藏了该Id字段为必填字段,这是例外。

我使用的数据库EntityData此处在msdn上进行了描述)的Id来源。我在MobileService上的使用Id是在执行该行时创建的,失败了db.SaveChanges()有人可以澄清一下吗?该类如下所示:

 public abstract class EntityData : ITableData
{
    protected EntityData();

    [Index(IsClustered = true)]
    [TableColumn(TableColumnType.CreatedAt)]
    public DateTimeOffset? CreatedAt { get; set; }
    [TableColumn(TableColumnType.Deleted)]
    public bool Deleted { get; set; }
    [TableColumn(TableColumnType.Id)]
    public string Id { get; set; }
    [TableColumn(TableColumnType.UpdatedAt)]
    public DateTimeOffset? UpdatedAt { get; set; }
    [TableColumn(TableColumnType.Version)]
    public byte[] Version { get; set; }
}
尔坎·德米雷尔

EF中不自动支持字符串主键。这就是为什么您应该手动分配主键的原因。

您可以initilaize IdCreatedDateUpdatedDate与构造。

    public abstract class EntityData : ITableData
    {
     //Change the constructor to initilaize required filled with meaningful data.
        protected EntityData()
        {
          Id=Guid.NewGuid().ToString();
          CreatedDate=DateTime.UtcNow;
          UpdatedDate=DateTime.UtcNow;
        }

        [Index(IsClustered = true)]
        [TableColumn(TableColumnType.CreatedAt)]
        public DateTimeOffset? CreatedAt { get; set; }
        [TableColumn(TableColumnType.Deleted)]
        public bool Deleted { get; set; }
        [TableColumn(TableColumnType.Id)]
        public string Id { get; set; }
        [TableColumn(TableColumnType.UpdatedAt)]
        public DateTimeOffset? UpdatedAt { get; set; }
        [TableColumn(TableColumnType.Version)]
        public byte[] Version { get; set; }
    }

您可以在上下文中覆盖savechanges方法。修改实体时,此方法将自动更改updateddate。

 public override int SaveChanges()
    {
        //Get Modified Entities
        var modifiedEntries = ChangeTracker.Entries()
             .Where(x => x.Entity is ITableData
                 && (x.State == EntityState.EntityState.Modified));
        foreach (var entry in modifiedEntries)
         {
           var entity = entry.Entity as ITableData;
           //Modify updateddate
           if (entity != null)
            {
              entity.UpdatedDate = DateTime.UtcNow;
            }
         }
        return base.SaveChanges();
    }

编辑:第一个解决方案是通用解决方案,不与任何库重新实现。

您需要序列化的EntityData当移动客户端和后端服务器尝试相互通信时,此类将为您提供帮助。例如,移动客户端不支持导航属性,但后端服务器支持。序列化实体数据时,它将为您隐藏这些属性。

如果您为此应用程序设计数据库。请遵循本文档

第一:您应该使用EntityData库内部的Class。您的模型应该继承自它而不是您的EntityDataClass。

第二:您的上下文应具有有关覆盖模型创建的代码。您需要使用它来自动更新在和ID处创建/更新的内容(这是您问题的答案)。

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            string schema = ServiceSettingsDictionary.GetSchemaName();
            if (!string.IsNullOrEmpty(schema))
            {
                modelBuilder.HasDefaultSchema(schema);
            }

            modelBuilder.Conventions.Add(
                new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
                    "ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
        }

如果您使用的数据库已经存在,请遵循本文档

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Net Core 3.0 Linux Azure Web App IHttpContextAccessor具有空上下文

来自分类Dev

失败-无法启动上下文路径/ my_app上的应用程序

来自分类Dev

Azure App Service Web App对VM的访问

来自分类Dev

Azure App Service Web App对VM的访问

来自分类Dev

Azure App Service / Web App是否取代Azure Cloud Service?

来自分类Dev

Azure App Service / Web App是否取代Azure Cloud Service?

来自分类Dev

Microsoft Azure App Service Storage

来自分类Dev

Google App Engine上下文。上下文与大猩猩上下文

来自分类Dev

Appium仅在Cordova App上显示NATIVE_APP上下文

来自分类Dev

来自Azure App Service的Blob存储访问

来自分类Dev

带有Azure App Service的ABCpdf .NET

来自分类Dev

将Springboot部署到Azure App Service

来自分类Dev

Azure App Service容器不断重启

来自分类Dev

如何管理Azure App Service证书

来自分类Dev

使用KeyVault的Azure App Service JSON转换

来自分类Dev

通过Azure创建App Service托管的证书

来自分类Dev

Azure Powershell脚本交换Azure App Service(网站)部署插槽

来自分类Dev

如何使用Azure Python SDK编辑Azure App Service?

来自分类Dev

无法连接到在Azure App Service上运行的KAFKA

来自分类Dev

对Azure App Service上的500.31 ANCM进行故障排除

来自分类Dev

如何在Azure Web App Service上获取IP地址

来自分类Dev

在Azure Web App上运行Selenium

来自分类Dev

在Azure Web App上找不到证书

来自分类Dev

使用托管身份允许Azure Function App向Azure App Service发出Http请求

来自分类Dev

在Azure App Service(Linux)上运行的Node / Next / React App是否需要web.config文件?

来自分类Dev

跨上下文LINQ是否加入Azure?

来自分类Dev

为什么我的Azure App Service Logic App无法使用我的API App?

来自分类Dev

为什么我的Azure App Service Logic App无法使用我的API App?

来自分类Dev

从非静态内部类引用App上下文

Related 相关文章

  1. 1

    Net Core 3.0 Linux Azure Web App IHttpContextAccessor具有空上下文

  2. 2

    失败-无法启动上下文路径/ my_app上的应用程序

  3. 3

    Azure App Service Web App对VM的访问

  4. 4

    Azure App Service Web App对VM的访问

  5. 5

    Azure App Service / Web App是否取代Azure Cloud Service?

  6. 6

    Azure App Service / Web App是否取代Azure Cloud Service?

  7. 7

    Microsoft Azure App Service Storage

  8. 8

    Google App Engine上下文。上下文与大猩猩上下文

  9. 9

    Appium仅在Cordova App上显示NATIVE_APP上下文

  10. 10

    来自Azure App Service的Blob存储访问

  11. 11

    带有Azure App Service的ABCpdf .NET

  12. 12

    将Springboot部署到Azure App Service

  13. 13

    Azure App Service容器不断重启

  14. 14

    如何管理Azure App Service证书

  15. 15

    使用KeyVault的Azure App Service JSON转换

  16. 16

    通过Azure创建App Service托管的证书

  17. 17

    Azure Powershell脚本交换Azure App Service(网站)部署插槽

  18. 18

    如何使用Azure Python SDK编辑Azure App Service?

  19. 19

    无法连接到在Azure App Service上运行的KAFKA

  20. 20

    对Azure App Service上的500.31 ANCM进行故障排除

  21. 21

    如何在Azure Web App Service上获取IP地址

  22. 22

    在Azure Web App上运行Selenium

  23. 23

    在Azure Web App上找不到证书

  24. 24

    使用托管身份允许Azure Function App向Azure App Service发出Http请求

  25. 25

    在Azure App Service(Linux)上运行的Node / Next / React App是否需要web.config文件?

  26. 26

    跨上下文LINQ是否加入Azure?

  27. 27

    为什么我的Azure App Service Logic App无法使用我的API App?

  28. 28

    为什么我的Azure App Service Logic App无法使用我的API App?

  29. 29

    从非静态内部类引用App上下文

热门标签

归档