gpt4 book ai didi

entity-framework - 在 Azure 移动服务 Controller 中添加相关的数据库条目

转载 作者:行者123 更新时间:2023-12-04 07:21:39 25 4
gpt4 key购买 nike

在我的 Azure 移动服务中,我有一个 Controller 类 UserController : TableController<User>其中有一个 get 方法:

// GET tables/User/48D68C86-6EA6-4C25-AA33-223FC9A27959
public SingleResult<User> GetUser(string id)
{
return Lookup(id);
}

我想在每次访问用户时进行记录,因此我向模型添加了一个简单的类型:

public class UserVisit : Microsoft.WindowsAzure.Mobile.Service.EntityData
{
public string VisitingUser { get; set; }
public DateTime TimeOfVisit { get; set; }
}

并包含属性 public DbSet<UserVisit> UserVisits { get; set; }在我的 VCollectAPIContext : DbContext类(并通过代码优先迁移更新数据库)。

要在查询用户 ID 时向数据库添加 UserVisit,我将 Controller 方法更改为

// GET tables/User/48D68C86-6EA6-4C25-AA33-223FC9A27959
public async Task<SingleResult<User>> GetUser(string id)
{
var userVisit = new UserVisit { VisitingUser = id, TimeOfVisit = DateTime.UtcNow };
context.UserVisits.Add(userVisit);
await context.SaveChangesAsync();
return Lookup(id);
}

但是 SaveChangesAsync失败并显示 System.Data.Entity.Validation.DbEntityValidationException .在异常的 EntityValidationErrors 中挖掘property 我发现问题是“需要 Id 字段。”

这有点奇怪。 Id 字段是基类 Microsoft.WindowsAzure.Mobile.Service.EntityData 中的属性之一。我希望在插入时自动添加。不管怎样,我可以添加它和其他几个基类的属性:

// GET tables/User/48D68C86-6EA6-4C25-AA33-223FC9A27959
public async Task<SingleResult<User>> GetUser(string id)
{
var userVisit = new UserVisit { Id = Guid.NewGuid().ToString(), Deleted = false, VisitingUser = id, TimeOfVisit = DateTime.UtcNow, CreatedAt = DateTimeOffset.Now };
context.UserVisits.Add(userVisit);
await context.SaveChangesAsync();
return Lookup(id);
}

这次我得到一个 System.Data.Entity.Infrastructure.DbUpdateException因为我们“无法将 NULL 值插入列‘CreatedAt’”。它在对 Add 的调用中不为空.所以CreatedAt已在我的代码之外的某处设置为空,结果插入失败!

我还尝试设置一个 EntityDomainManager<UserVisit> userVisitDomainManager; Controller 初始化器中的实例变量,然后将我的 Controller get 方法重写为

// GET tables/User/48D68C86-6EA6-4C25-AA33-223FC9A27959
public async Task<SingleResult<User>> GetUser(string id)
{
var userVisit = new UserVisit { VisitingUser = id, TimeOfVisit = DateTime.UtcNow };
await userVisitDomainManager.InsertAsync(userVisit);
return Lookup(id);
}

失败并显示相同的消息,“无法将值 NULL 插入列 'CreatedAt'”

我应该如何执行在我的 Controller 方法中插入相关数据项这一看似简单的任务?

最佳答案

解决方案可能类似于 this answer .我猜您的迁移未使用移动服务 SqlGenerator,因此未应用某些自定义 SQL 设置。这意味着:

  • Id 没有获得默认值 NEWID() - 这解释了您的“需要 Id 字段”错误。
  • CreatedAt 没有获得 SYSUTCDATETIME() 的默认值——这与 EntityData.CreatedAt 上的 [DatabaseGenerated] 属性相结合,解释了“NULL CreatedAt”错误。

尝试根据上面的链接更新您的迁移,看看是否适合您。

关于entity-framework - 在 Azure 移动服务 Controller 中添加相关的数据库条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32181294/

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