Add related database entry in Azure Mobile Services controller

故事扮演 提交于 2019-12-12 09:53:38

问题


In my Azure Mobile Service I have a controller class UserController : TableController<User> and in it is a get method:

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

I want to record each time a user is accessed and so I add a simple type to the model:

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

and include the property public DbSet<UserVisit> UserVisits { get; set; } in my VCollectAPIContext : DbContext class (and update the database with a code-first migration).

To add a UserVisit to the database when a user id is queried I change my controller method to

// 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);
}

But the SaveChangesAsync fails with a System.Data.Entity.Validation.DbEntityValidationException. Digging around in the exception's EntityValidationErrors property I find that the problem is "The Id field is required."

That's a little odd. The Id field is one of the properties in the base-class Microsoft.WindowsAzure.Mobile.Service.EntityData that I would expect to be added automatically on insert. No matter, I can add it and several of the other base-class's properties thus:

// 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);
}

This time I get a System.Data.Entity.Infrastructure.DbUpdateException because we "Cannot insert the value NULL into column 'CreatedAt'". It was not null in the call to Add. So CreatedAt has been set to null somewhere outside my code and then the insert fails as a result!

I also tried setting up an EntityDomainManager<UserVisit> userVisitDomainManager; instance variable in the controller's initializer, and then rewriting my controller get method as

// 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);
}

That fails with the same message, "Cannot insert the value NULL into column 'CreatedAt'"

How should I perform the seemingly simple task of inserting a related data item within my controller method?


回答1:


The solution is likely similar to this answer. I'm guessing that your migration is not using the Mobile Services SqlGenerator so some of the custom SQL settings aren't getting applied. What that means is that:

  • Id doesn't get a default value of NEWID() -- this explains your "Id field is required" error.
  • CreatedAt doesn't get a default value of SYSUTCDATETIME() -- this, combined with the [DatabaseGenerated] attribute on EntityData.CreatedAt, explains the "NULL CreatedAt" error.

Try updating your migration according to the link above and see if that works for you.




回答2:


To fix the problem of "The Id field is required" following brettsam's instructions.

Add this in your model:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[TableColumn(TableColumnType.Id)]
public new string Id { get; set; }

It will auto generate a GUID when you add an entity.



来源:https://stackoverflow.com/questions/32181294/add-related-database-entry-in-azure-mobile-services-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!