/
TodoSimpleOData.cs
85 lines (78 loc) · 2.58 KB
/
TodoSimpleOData.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Net.Http;
using System.Threading.Tasks;
using BlazorOData.Models;
using Simple.OData.Client;
namespace BlazorOData.Client.Models
{
public class TodoSimpleOData : ITodoDataAccess
{
private readonly IODataClient _client;
public TodoSimpleOData(HttpClient client)
{
client.BaseAddress = new Uri("http://localhost:5000/odata/");
var settings = new ODataClientSettings(client);
_client = new ODataClient(settings);
}
public async Task<Todo> AddAsync(Todo itemToAdd)
{
var results = new List<ValidationResult>();
var validation = new ValidationContext(itemToAdd);
if (Validator.TryValidateObject(itemToAdd, validation, results))
{
return await _client.For<Todo>().Set(itemToAdd).InsertEntryAsync();
}
else
{
throw new ValidationException();
}
}
public async Task<bool> DeleteAsync(Todo item)
{
await _client.For<Todo>().Key(item.Id).DeleteEntryAsync();
return true;
}
public async Task<IEnumerable<Todo>> GetAsync(bool showAll, bool byCreated, bool byCompleted)
{
var helper = _client.For<Todo>();
if (!showAll)
{
helper.Filter(todo => !todo.Complete);
}
if (showAll && byCompleted)
{
helper.OrderByDescending(todo => todo.MarkedComplete)
.ThenByDescending(todo => todo.Created);
}
else if (byCreated)
{
helper.OrderByDescending(todo => todo.Created);
}
else
{
helper.OrderBy(todo => todo.Description);
}
return await helper.FindEntriesAsync();
}
public Task<Todo> GetAsync(int id)
{
throw new NotImplementedException();
}
public async Task<Todo> UpdateAsync(Todo item)
{
var results = new List<ValidationResult>();
var validation = new ValidationContext(item);
if (Validator.TryValidateObject(item, validation, results))
{
await _client.For<Todo>().Key(item.Id).Set(item).UpdateEntryAsync();
return item;
}
else
{
throw new ValidationException();
}
}
}
}