Get data from database with where clause using API - api

I have a table named SerialNumbers containing some columns in it.
I want to get the data with SNum based on scanned value which has been listed in an Array.
Below is my code:
public class SNController : ApiController
{
[HttpGet]
public HttpResponseMessage AllSN()
{
using (SNDBContext dbContext = new SNDBContext())
{
string[] SNum = { "01070A2", "01070A3", "01070A4" };
var SerialNum = dbContext.SNumbers.Where(x => x.SN == "01070A2")
.Select(p => new { p.Name, p.Status})
.ToList();
return Request.CreateResponse(HttpStatusCode.OK, SerialNum );
}
}
When I try to hardcoded this part var SerialNum = dbContext.SNumbers.Where(x => x.SN == "01070A2"), its working.
How can I solve this issue?

Use Contains method in Where clause.
var SerialNum = dbContext.SNumbers.Where(x => SNum.Contains(x.SN))
.Select(p => new { p.Name, p.Status})
.ToList();

Related

RavenDB - Adding Index breaks unrelated queries

When I add the index below to my raven database a simple query like
return Session.Query<R>().FirstOrDefault(x => x.RId == Id);
Always returns null. Only after forcing Raven to remove my custom index does desired functionality return. Why is this?
The Index with side effects:
public class RByLatestCommentIndex : AbstractIndexCreationTask<R>
{
public RByLatestCommentIndex()
{
SetMap();
}
void SetMap()
{
Map = r => r.Select(x => new
{
Id = x.Id,
TimeStamp = x.Comments.Count() > 0 ? x.Comments.Max(u => u.Created)
: x.Created
}).OrderByDescending(y => y.TimeStamp).Select(r => new { Id = r.Id });
}
}
public class RIdTransformer : AbstractTransformerCreationTask<R>
{
public RIdTransformer()
{
TransformResults = ids => ids.Select(x => LoadDocument<R>(x.Id));
}
}
EDIT:
In response to Ayende Rahien's comment:
There's a query in the DB which would otherwise be used (Auto/R/ByRID) but the index used looks like this, puzzling enough:
from doc in docs.Rs select new { Images_Count__ = doc.Images["Count()"], RId = doc.RId }
What explains this behaviour? And, will I have to add a static index to be able to query R by RId ?

NHibernate: how to use ExpandoResultTransformer with Session.QueryOver

I have created a ExpandoResultTransformer, that would be used for converting query results to dto to be used in UI. It looks like this:
public class ExpandoResultTransformer : IResultTransformer
{
public object TransformTuple(object[] tuple, string[] aliases)
{
dynamic toReturn = new ExpandoObject();
for (int i = 0; i < aliases.Length; i++)
{
((IDictionary<string, object>)toReturn)[aliases[i]] = tuple[i];
}
return toReturn;
}
public IList TransformList(IList collection)
{
return collection;
}
}
When I use it against a createSQLQuery it works perfectly
var contacts = _session.CreateSQLQuery("exec up_ClientContactsView #ClientId=:clientId")
.SetParameter("clientId", request.ClientId)
.SetResultTransformer(new ExpandoResultTransformer())
.List<dynamic>();
However, when I tried using it against QueryOver, I run into trouble. There are no aliases sent in. So I tried specifying them like this
var periodTables = _session.QueryOver<PeriodTable>()
.Where(x => x.ClientPolicy.Id == request.ClientPolicyId)
.SelectList(list => list
.Select(i =>i.Id).WithAlias(()=>info.PeriodTableId) !! does not work as dynamic cannot be used in expression error
.Select(i => i.Id).WithAlias(()=>"PeriodTableId" !!! does not work either as it cannot find member error
.TransformUsing(new ExpandoResultTransformer())
.List<dynamic>();
Any ideas how to pass in aliases?
You can use an anonymous type instance to act as a template object:
var template = new { PeriodTableId = 0 };
var periodTables = _session.QueryOver<PeriodTable>()
.Where(x => x.ClientPolicy.Id == request.ClientPolicyId)
.SelectList(list => list
.Select(i =>i.Id).WithAlias(()=>template.PeriodTableId)
)
.TransformUsing(new ExpandoResultTransformer())
.List<dynamic>();

Select or SelectList: I Want to include the entire entity

I am querying a list of objects, and then correlating them with a subquery.
I want to return the results of the subquery, as well as the root entity. But
I can't figure out how to actually return the root entity, I can only return individual properties of it.
Specifically, this works:
this.Session.QueryOver<MediaFile>(() => mediaFile)
.SelectList(list => list.Select(mf => mf.Id));
But this does not:
this.Session.QueryOver<MediaFile>(() => mediaFile)
.SelectList(list => list.Select(mf => mf));
I get the following error:
Could not resolve property : of MediaFile
Does anyone know how I can include the entity as a property in the list?
Here's my complete example:
// My target class
private class MediaFileAndCount
{
// I can successfully populate these fields.
public long MediaFileId { get; set; }
public int DistinctPlaylistCount { get;set; }
// But I want to populate this field!
public MediaFile MediaFile { get; set; }
}
private void TrySingleQuery()
{
MediaFile mediaFile = null;
PlaylistEntry playlistEntry = null;
MediaFileAndCount mfc = null;
var subQuery = QueryOver.Of<PlaylistEntry>(() => playlistEntry)
.Where(() => playlistEntry.MediaFile.Id == mediaFile.Id)
.Select(Projections.CountDistinct<PlaylistEntry>(p => p.Playlist));
var query = this.Session.QueryOver<MediaFile>(() => mediaFile)
.SelectList(list => list
.Select(mf => mf.Id).WithAlias(() => mfc.MediaFileId)
.Select(Projections.SubQuery(subQuery)).WithAlias(() => mfc.DistinctPlaylistCount)
// .Select(mf => mf).WithAlias(() => mfc.MediaFile) // This line fails
)
.TransformUsing(Transformers.AliasToBean<MediaFileAndCount>());
var results = query.List<MediaFileAndCount>();
}
another way to query it
var allMediaFiles = session.QueryOver<MediaFile>().Where(...).ToFuture(); // just get the MediaFiles into sessionCache
var results = session.QueryOver<PlaylistEntry>()
.Where(p => p.MediaFile...)
.SelectList(list => list
.GroupBy(p => p.MediaFile.Id)
.CountDistinct(p => p.Playlist))
.ToFuture<object[]>()
.Select(a => new MediaFileAndCount
{
MediaFile = session.Get<MediaFile>((long)a[0]),
DistinctPlaylistCount = (int)a[1]
})
.ToList();
foreach (var mediaFile in allMediaFiles.Except(results.Select(r => r.MediaFile)))
{
results.Add(new MediaFileAndCount { MediaFile = mediaFile });
}

Filtering navigation property in eager loading with NHibernate with LINQ

I use this in EF
var users = Context.CreateSet<User>()
.Select(u => new {
User = u,
Salary = u.Salaries.Where(s => !s.Deleted)
})
.AsEnumerable()
.Select(a => a.User);
There is a Linq way to do this in NHibernate and i want it work for navigation property load by lazy load too
NHibernate will not fill the collection with filtered results this way and it is not a good idea because you get a broken model. The best options i see
var users = session.Query<User>()
.Fetch(u => u.Salaries)
.Select(u => new
{
User = u,
ActiveSalaries = u.Salaries.Where(s => !s.Deleted)
});
or
public virtual IEnumerable<Salary> ActiveSalaries
{
get { return Salaries.Where(s => !s.Deleted); }
}
var users = session.Query<User>()
.Fetch(u => u.Salaries)
or
// ctor
ActiveSalaries = Salaries.Where(s => !s.Deleted);
// property
public virtual IEnumerable<Salary> ActiveSalaries { get; private set; }
// mapping almost same as that of Salaries
HasMany(x => x.ActiveSalaries).Table("Salaries").Where("Deleted=0");
var users = session.Query<User>()
.Fetch(u => u.ActiveSalaries);

RavenDB Index is not working when using SelectMany in Map Function

Based on this article from Ayende i have created the following index definition
public class ProductsSearch : AbstractIndexCreationTask<Product, ProductsSearch.Result>
{
public class Result
{
public string Query { get; set; }
}
public ProductsSearch()
{
Map = products => from product in products
select new
{
Query = new object[]
{
product.Title,
product.Tags.Select(tag => tag.Name),
product.Tags.SelectMany(tag => tag.Aliases, (tag, alias) => alias.Name)
}
};
Index(x => x.Query, FieldIndexing.Analyzed);
}
}
One difference is that i must use a SelectMany statement to get the aliases of a tag.
A tag can have many aliases (i. e. tag: mouse alias:pointing device)
I have no idea why the SelectMany line breaks the index. If i remove it, the index works.
This should work:
Map = products => from product in products
from tag in product.Tags
from alias in tag.Aliases
select new
{
Query = new object[]
{
product.Title,
tag.Name,
alias.Name
}
};