Repost model class:
public class TransactionDayReport
{
public Decimal TotalAmount { get; set; }
public ICollection<TransactionResponse> TransactionResponses { get; set; } = null!;
}
This is my repository method
public async Task<IEnumerable<Transaction>> SearchTransactionAsync(SearchTransaction search)
{
var query = _context.Transactions
.Include(t => t.Branch)
.Include(t => t.Customer)
.AsQueryable();
if (search.CIN != null)
query = query.Where(t => t.Customer.CIN.Contains(search.CIN));
if (search.ValueDate != null)
query = query.Where(t => t.ValueDate.Date == search.ValueDate.Date);
return await query.ToListAsync();
}
Service method:
public async Task<TransactionResponse> SearchTransactions(SearchTransaction search)
{
var transactionList = await _unitOfWork.Transactions.SearchTransactionAsync(search);
var mapped = ObjectMapper.Mapper.Map<TransactionDayReport>(transactionList);
return mapped;
}
I need to send total amount in service class..
am looking similar to this
But I am confused how to get addition sum added to my dto. Please can anyone suggest a solution? Thanks
The only way to also calculate the sum on the DB is to run another query on the DB, unless the DB query can be re-written to return both the sum and the data.
If you're ok with calculating the Sum on the client, it's more straightforward. Here are some options I could think of:
You could configure the mapper to set the sum.
You could set the sum after performing the mapping in SearchTransactions().
You could change the DTO to calculate the Sum (in which case it wouldn't be a POCO anymore, but I think this is a reasonable approach too):
public class TransactionDayReport
{
private decimal? _totalAmount = null;
public decimal TotalAmount { get {
if(_totalAmount is not null) return _totalAmount; // new C# 9 feature :)
_totalAmount = // calculate total amount here
return _totalAmount;
}
public ICollection<TransactionResponse> TransactionResponses { get; set; } = null!;
}
Related
I have an index.chtml set up with about 10 ActionLinks. Those actionLinks trigger different ActionResult functions within the controller since each of them essentially perform unique queries on a data model.
I also have an entities object named db which has all the data. Instead of just displaying all the data, I want to perform complex filtering on the entities object to find where certain properties of records are null or where a property is greater than some input then returns a view of all columns on only those records that were filtered.
Find nulls:
public class printJobsController : Controller {
private PrintJobsEntities db = new PrintJobsEntities
public ActionResult IncompleteJobs {
//get jobs where processDate is null
...
}
}
Find where count is greater than 10:
public class printJobsController : Controller {
private PrintJobsEntities db = new PrintJobsEntities
public ActionResult JobsGreaterThan(int limit) {
//group by printerName and find counts greater than limit
...
}
}
How do I go about doing this?
Seems you are trying to populate the View with filtered data as per your request parameter in controller action.
You could follow the below steps to achieve what you are trying to:
Your imaginary Data Model
public class PrinterJob
{
[Key]
public int PrinterId { get; set; }
public string PrinterName { get; set; }
public int PrintedBy { get; set; }
public int TotalPrint { get; set; }
}
Sample Data In Database:
Controller Action:
public ActionResult <PrinterJob> JobsGreaterThan(int limit) {
var printCountByGroup =
(from objPrint in _context.PrinterJobs group objPrint by new {
objPrint.PrinterName, objPrint.PrintedBy, objPrint.TotalPrint
}
into grp where grp.Sum(p => p.TotalPrint) > limit
select new {
PrinterName = grp.Key.PrinterName, PrintedBy = grp.Key.PrintedBy,
TotalPrint = grp.Key.TotalPrint
});
return View(printCountByGroup);
}
Output After Applying Filter:
Note: Here I am trying to filter printer information which printed more then 30 printing jobs.
Hope it would help you to achieve your goal. If you still have any problem feel free to let me know.
I have the following model class-
public partial class Settings
{
public int Id { get; set; }
public string Value { get; set; }
public string Name { get; set; }
}
Inside my asp.net core MVC 3.1, i want to only get the Value of a single item, now i can NOT do this:-
var result = await _context.Settings.SingleOrDefaultAsync(a => a.Name.ToLower() == "noofvisits").Value;
and the only way is to first get the whole object from the database and then get its Value, as follow:-
var result = await _context.Settings.SingleOrDefaultAsync(a => a.Name.ToLower() == "noofvisits");
var val = result.Value;
but to make my code more efficient how i can directly get the Value property from the database asynchronously ?
You should use Raw Sql query.
Try this :
var result = await _context.Settings.FromSql("SELECT Top(1) NAME FROM dbo.Settings ").SingleOrDefaultAsync();
Try the below statement:
var result = await _context.Settings.Where(a => a.Name.ToLower() == "noofvisits").Select(o => o.Value).FirstOrDefaultAsync();
I'm attempting to return a true or false (in JSON) along with my model data. Code builds and runs fine but I only get a return on my model data.
What I've tried from reading other answers:
public IQueryable<Book> GetBooks()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
return db.Books;
}
As you can probably easily see, I don't have the greatest idea of what I'm doing, but through the infinite wisom of this community I hope to learn another feat.
I would create a view model and returned that from the controller
public class BooksVm
{
public IQueryable<Book> Books { get; set; }
public bool BooleanValue { get; set; }
}
and then in your controller
public IHttpActionResult GetBooks()
{
var booksVm = new BooksVm() { Books = db.Books, BooleanValue = true };
return Ok(booksVm);
}
We have a Web app (ASP.NET/C#) with SQL Server backend. We use ServiceStack OrmLite as our POCO Micro ORM. We would now like to extend a part of our app to cache frequently-read data (mainly a collection of POCO objects as values, with numeric keys). But I'm not sure how to go about integrating a simple caching solution (in-memory or Redis based) that works seamlessly with OrmLite and MSSQL as the Master database.
I've read about the ServiceStack Redis Client, MemoryCacheClient and Multi nested database connections (OrmLiteConnectionFactory), but I couldn't find any examples, tutorial or code samples to learn more about implementing caching that works with OrmLite.
Any suggestions or links will be helpful and much appreciated.
I use this extension to help simplify the integration between the db and the cache.
public static class ICacheClientExtensions
{
public static T ToResultUsingCache<T>(this ICacheClient cache, string cacheKey, Func<T> fn, int hours = 1) where T : class
{
var cacheResult = cache.Get<T>(cacheKey);
if (cacheResult != null)
{
return cacheResult;
}
var result = fn();
if (result == null) return null;
cache.Set(cacheKey, result, TimeSpan.FromHours(hours));
return result;
}
}
public class MyService : Service
{
public Data Get(GetData request)
{
var key = UrnId.Create<Data>(request.Id);
Func<Data> fn = () => Db.GetData(request.Id);
return Cache.ToResultUsingCache(key, fn);
}
[Route("/data/{id}")]
public class GetData: IReturn<Data>
{
public int Id{ get; set; }
}
}
You'd need to implement the caching logic yourself, but it's not much work - here's a pseudocode example:
public class QueryObject
{
public DateTime? StartDate { get; set; }
public string SomeString { get; set; }
}
public class Foo
{
public DateTime DateTime { get; set; }
public string Name { get; set; }
}
public class FooResponse
{
public List<Dto> Data { get; set; }
}
public FooResponse GetFooData(QueryObject queryObject)
{
using (var dbConn = connectionFactory.OpenDbConnection())
using (var cache = redisClientsManager.GetCacheClient())
{
var cacheKey = string.Format("fooQuery:{0}", queryObject.GetHashCode()); //insert your own logic for generating a cache key here
var response = cache.Get<Response>(cacheKey);
//return cached result
if (response != null) return response;
//not cached - hit the DB and cache the result
response = new FooResponse()
{
Data =
dbConn.Select<Foo>(
x => x.DateTime > queryObject.StartDate.Value && x.Name.StartsWith(queryObject.SomeString)).ToList()
};
cache.Add(cacheKey, response, DateTime.Now.AddMinutes(15)); //the next time we get the same query in the next 15 mins will return cached result
return response;
}
}
Have you checked Service stack caching wiki. It gives detailed info about caching. Now in your case from the details you are providing I can say that you can go for any kind of caching. As of now it will not make any difference.
PS: A piece of advice caching should be done when there is no option or the only thing pending in application. Because it comes with it's own problem is invalidating caching, managing and all that. So, if you application is not too big, just leave it for now.
I need to make a query against a document collection that matches several properties.
(Cross post from the mailing list: https://groups.google.com/forum/?fromgroups=#!topic/ravendb/r5f1zr2jd_o)
Here is the document:
public class SessionToken
{
[JsonProperty("jti")]
public string Id { get; set; }
[JsonProperty("aud")]
public Uri Audience { get; set; }
[JsonProperty("sub")]
public string Subject { get; set; }
[JsonProperty("claims")]
public Dictionary<string, string> Claims { get; set; }
}
And here is the test:
[TestFixture]
public class RavenDbTests
{
private IDocumentStore documentStore;
[SetUp]
public void SetUp()
{
this.documentStore = new EmbeddableDocumentStore() { RunInMemory = true };
this.documentStore.Initialize();
}
[Test]
public async void FirstOrDefault_WhenSessionTokenExists_ShouldReturnSessionToken()
{
var c = new SessionToken()
{
Audience = new Uri("http://localhost"),
Subject = "NUnit",
Claims = new Dictionary<string, string>()
{
{ ClaimTypes.System, "NUnit" }
}
};
using (var session = this.documentStore.OpenAsyncSession())
{
await session.StoreAsync(c);
await session.SaveChangesAsync();
// Check if the token exists in the database without using Where clause
var allTokens = await session.Query<SessionToken>().ToListAsync();
Assert.That(allTokens.Any(x => x.Subject == "NUnit" && x.Audience == new Uri("http://localhost")));
// Try getting token back with Where clause
var token = await session.Query<SessionToken>().Customize(x => x.WaitForNonStaleResults()).Where(x => x.Subject == "NUnit" && x.Audience == new Uri("http://localhost")).ToListAsync();
Assert.IsNotNullOrEmpty(token.First().Id);
}
}
}
The last Assert is the one that is failing.
I must admit Im not sure whether this is a bug or a failure on my part.
As far as I understand, this is supposed to work.
PS. I´ve tried with a standalone document store as well as embedded without running in memory, but with same result.
You are getting stale results. In a unit test, you need to allow time for indexing to occur.
Add .Customize(x=> x.WaitForNonStaleResults()) to your queries and the test should pass.
Also, I think you left the Id property off your question when you cut/paste because it doesn't compile as-is.
UPDATE
Per discussion in comments, the issue was that you were applying the [JsonProperty] attribute to the Id property. Since the Id property represents the document key, and is not serialized as part of the JSON document, you can't apply the [JsonProperty] attribute to it.