gpt4 book ai didi

azure - 使用 TableController 和 AzureMobileApps 发布新实体时出现错误 500

转载 作者:行者123 更新时间:2023-12-03 00:29:31 25 4
gpt4 key购买 nike

我在 AzureMobileApps 上使用 TableController 时遇到问题。我使用脚手架在 Visual Studio 中创建了一个新的 Azure Mobile App TableController。在帖子中,我修改了生成的代码,在 dbContext 上添加了附加,以避免在子表上插入期间创建引用的项目。这就是生成的代码:

 public async Task<IHttpActionResult> PostLocation(Location item)
{
_context.Accounts.Attach(item.LocationAccount);
_context.Categories.Attach(item.PrimaryCategory);

Location current = await InsertAsync(item);
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}

问题是,每次调用 post 方法时,即使实体已正确插入,我也会在“CreatedAtRoute”事件上收到 500 内部服务器错误。

知道问题出在哪里吗?!

更新:实体模型

public class Account : EntityData
{
public Account()
{
this.Locations = new HashSet<Location>();
}

[Required]
public string Username { get; set; }

[Required]
public string FirstName { get; set; }

[Required]
public string LastName { get; set; }

public virtual ICollection<Location> Locations { get; private set; }
}

public class Location : EntityData
{
[Required]
public Account LocationAccount { get; set; }

........
}

谢谢大家。

最佳答案

据我所知,在添加Attach相关代码之前,如果LocationAccountPrimaryCategory是新项目,那么它们将被自动创建。如果其中任何一个(LocationAccountPrimaryCategory)存在于数据库表中,那么您将检索 409 状态代码。

根据我的测试,添加Attach相关代码后,如果LocationAccountPrimaryCategory存在,那么您可以创建新的Location 项目成功。但如果其中任何一个不存在,那么您可能会收到如下错误:

enter image description here

根据我的理解,您需要检查 Location 的导航属性是否存在。对于现有的导航属性项,您可以使用DbSet.Attach方法来阻止附加实体的插入,而新的导航属性项,您需要使用DbSet.Add或者什么也不做。

此外,您可以在 Startup.MobileApp.cs 文件的 ConfigureMobileApp 方法中添加以下代码,以包含错误详细信息并返回到客户端。

config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

更新:

默认情况下,将插入引用的实体(LocationAccountPrimaryCategory),如果存在任何实体,那么您将收到 409,如下所示:

enter image description here

添加_context.Accounts.Attach(item.LocationAccount);后,您可以创建与现有引用实体(LocationAccount)有关系的Location实体,PrimaryCategory),如果引用的实体 (LocationAccount,PrimaryCategory) 不存在,您将收到以下错误:

enter image description here

对于您的场景,您发布位置的现有引用实体(LocationAccountPrimaryCategory)。即使可以成功创建位置项,但根据您的实体模型,您可能会遇到如下 500 错误:

enter image description here

您可以将 Account 实体模型中的 Locations 属性标记为 JsonIgnore。或者您需要修改实体模型以在处理序列化时忽略引用循环。

此外,您可以利用以下代码片段来代替 CreatedAtRoute

return Json(current, new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});

我还尝试按如下方式在 Startup.MobileApp.cs 下设置 SerializerSettings 的全局设置,但它无法按预期工作。

config.Formatters.JsonFormatter.SerializerSettings.Re‌​ferenceLoopHandling = ReferenceLoopHandling.Ignore;

此外,您可以关注Loop Reference handling in Web API了解更详细的方法。

关于azure - 使用 TableController 和 AzureMobileApps 发布新实体时出现错误 500,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48891640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com