【问题标题】:Problem using Where() for Azure Mobile Service将 Where() 用于 Azure 移动服务的问题
【发布时间】:2018-11-13 02:37:18
【问题描述】:

我有以下不起作用的测试:

public class DesktopDTO
{
    public DesktopDTO() {}
    public DesktopDTO(string title, Guid otherId) 
    {
         Id = Guid.NewGuid();
         Title = title;
         OtherId = otherId;
    }
    public Guid Id { get; set; }
    public string Title { get; set; }
    public Guid OtherId { get; set; }
}

//setup environment:
MobileServiceClient mobileService = new MobileServiceClient("http://myserver.azurewebsites.net/");
IMobileServiceSyncTable<DesktopDTO> table = mobileService.GetSyncTable<DesktopDTO>();
if (!mobileService.SyncContext.IsInitialized)
{
    var store = new MobileServiceSQLiteStore("localstore1.db");
    store.DefineTable<DesktopDTO>();
    await mobileService.SyncContext.InitializeAsync(store);
}
DesktopDTO input = new DesktopDTO("test124", Guid.NewGuid()); //this is my entity

//invoke action:
await table.InsertAsync(input);

//check results:
List<DesktopDTO> all = await table.ToListAsync();  //this returns 1 item
DesktopDTO r1 = all.Where(x => x.Id == input.Id).FirstOrDefault();  //this returns the created item
var query12 = await table.Where(x => x.Title == "test124").ToCollectionAsync(); //this returns 1 item
DesktopDTO r = (await table.Where(x => x.Id == input.Id).ToCollectionAsync()).FirstOrDefault(); //this returns null!!

问题是最后一个本地查询,它使用由 Id 过滤的 Where() 子句(这是 DesktopDTO 实体的 PK),没有返回想要的实体。

实体已在数据库中正确插入(如其他查询所示,即使是按“标题”过滤的实体),所以我不明白为什么 Where() 过滤器不应仅与 PK 一起使用。

我也尝试过使用LookupAsync() 方法,但还是没有结果。

我做错了什么?

谢谢!

【问题讨论】:

  • 您是否尝试过将 id 作为变量而不是直接在表达式中传递?
  • 是的,结果一样 :(

标签: c# sqlite azure azure-mobile-services


【解决方案1】:

我尝试重现我这边的问题。但我得到了 ArgumentException:“ID 必须是字符串类型”。

如果我将 ID 类型从 Guid 更改为 string,我将无法重现您提到的问题。我的工作正常。

public class DesktopDTO
    {
        public DesktopDTO() { }
        public DesktopDTO(string title, Guid otherId)
        {
            Id = Guid.NewGuid().ToString();
            Title = title;
            OtherId = otherId;
        }
        public string Id { get; set; }
        public string Title { get; set; }
        public Guid OtherId { get; set; }

    }

测试结果:

【讨论】:

    【解决方案2】:

    为了将来参考,我发现了问题。

    Azure 移动服务不允许(本机)具有 GUID 等字段。但它接受 Guid 并使用 UPPER CASE 默默地将它们转换为字符串。

    因此,解决方案是在查询中将所有 Guid 转换为大写。

    您可以:

    DesktopDTO r = (await table.Where(x => x.Id.ToString.ToUpper() == input.Id.ToString.ToUpper()).ToCollectionAsync()).FirstOrDefault();
    

    或直接:

    DesktopDTO r = await table.LookupAsync(id.ToString().ToUpper());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多