I have the following class defined
public class IRM_TEMP_Appointment_archive
{
public virtual String VisitNumber { get; set; }
public virtual String WardCode { get; set; }
public virtual String ClinicCode { get; set; }
public virtual String DoctorCode { get; set; }
public virtual String AppointmentStatusCode { get; set; }
public virtual String PatientNumber { get; set; }
public virtual String EpisodeNumber { get; set; }
public virtual String ConsultantCode { get; set; }
public virtual String ReferrerCode { get; set; }
public virtual String MainSpecialtyCode { get; set; }
public virtual String MessageType { get; set; }
public virtual String EpisodeStatusCode { get; set; }
public virtual String ParentEpisodeType { get; set; }
public virtual String AdmissionType { get; set; }
public virtual String AdmitReason { get; set; }
public virtual String BuildingCode { get; set; }
public virtual String BedNumber { get; set; }
public virtual String CategoryCode { get; set; }
public virtual String ConsultantName { get; set; }
public virtual String DischargeDestination { get; set; }
public virtual String DischargeMethod { get; set; }
public virtual String FacilityCode { get; set; }
public virtual String ReferralReason { get; set; }
public virtual String ReferrerAssigningAuthority { get; set; }
public virtual String ReferrerName { get; set; }
public virtual String currentStatus { get; set; }
public virtual String AppointmentTypeText { get; set; }
public virtual String TCILocation { get; set; }
public virtual Boolean analysed { get; set; }
public virtual DateTime AdmitDateTime { get; set; }
public virtual DateTime StopDateTime { get; set; }
public virtual DateTime ScheduledDateTime { get; set; }
public virtual DateTime AppointmentDateTime { get; set; }
public virtual DateTime DischargeDateTime { get; set; }
public virtual DateTime timeOfInsert { get; set; }
public virtual DateTime timeOfAnalyse { get; set; }
public virtual DateTime TCIDate { get; set; }
public virtual int TempAppointmentKey { get; set; }
I need to find any appointments a patient has on a given date, for this I need to extract just the date
using (ISessionFactory factory = CreateSessionFactory())
{
using (var session = factory.OpenSession())
{
var query = session.QueryOver<IRM_TEMP_Appointment_archive>()
.Where(a => (a.PatientNumber == MRN) && (a.AppointmentDateTime.ToShortDateString() == DateOfAppointment.ToShortDateString()))
.List()
.ToList<IRM_TEMP_Appointment_archive>();
if (query != null)
{
results = query;
}
}
}
However when this code executes I am getting an error
Unrecognised method call in epression a.AppointmentDateTime.ToShortDateString()
I presume that is because it is unable to determine the SQL for ToShortDateString - so how should I code this requirement. Database is SQL Server.
I assume you are looking for something like this (this is using the Linq provider and not QueryOver):
[Test]
public void CanQueryByDate()
{
var x = (from o in db.Orders
where o.OrderDate.Value.Date == new DateTime(1998, 02, 26)
select o).ToList();
Assert.AreEqual(6, x.Count());
}
The unit tests are generally a good place to find basic examples. See here for the nhibernate unit tests for linq that are specific to date time examples:
https://github.com/nhibernate/nhibernate-core/blob/master/src/NHibernate.Test/Linq/DateTimeTests.cs
The query is split into two, with the date check done in the second half on the result of querying on the patient identifier. So the if statement at the end becomes;
if (query != null)
{
results = (from a in query where a.AppointmentDateTime.Date == DateOfAppointment.Date select a).ToList<IRM_TEMP_Appointment_archive>();
}
Because the later query is not being converted into T-SQL then there is no concern on their being no equivalent of the Date function.
Related
I'm trying to seed a database using EF.
I have a table that holds products (phones) and a Category table that differentiates between different types of products.
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public DateTimeOffset? CreationDate { get; set; }
public DateTimeOffset? UpdateDate { get; set; }
public virtual List<IProduct> Products{ get; set; }
public Category()
{
this.CreationDate = DateTimeOffset.UtcNow;
}
}
public interface IProduct
{
int ProductId { get; set; }
string Brand { get; set; }
string Model { get; set; }
decimal? Price { get; set; }
string Image { get; set; }
int CategoryId { get; set; }
Category Category { get; set; }
}
public class Phone: IProduct
{
public int ProductId { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
public string Brand { get; set; }
public string Model { get; set; }
public string network_technology { get; set; }
public string bands_2G { get;set; }
public string bands_3G{ get; set; }
public string bands_4G { get; set; }
public string network_speed { get; set; }
public string GPRS { get; set; }
public string EDGE { get; set; }
public string announced { get; set; }
public string status { get; set; }
public string dimentions { get; set; }
public float? weight_g { get; set; }
public float? weight_oz { get; set; }
public string SIM { get; set; }
public string display_type { get; set; }
public string display_resolution { get; set; }
public string display_size { get; set; }
public string OS { get; set; }
public string CPU { get; set; }
public string Chipset { get; set; }
public string GPU { get; set; }
public string memory_card { get; set; }
public string internal_memory { get; set; }
public string RAM { get; set; }
public string primary_camera { get; set; }
public string secondary_camera { get; set; }
public string loud_speaker { get; set; }
public string audio_jack { get; set; }
public string WLAN { get; set; }
public string bluetooth { get; set; }
public string GPS { get; set; }
public string NFC { get; set; }
public string radio { get; set; }
public string USB { get; set; }
public string sensors { get; set; }
public string battery { get; set; }
public string colors { get; set; }
public decimal? Price { get; set; }
public string Image { get; set; }
}
I don't know what am I doing wrong but after I update the database from nuget console, a new Category record is created per seeded product(phone). That's exactly the opposite of what I want. I want all the phones to have one categoryId that refers to Phones category. does anyone know what's wrong?
Entity Type Configurations (fluent api):
public class CategoryConfiguration : EntityTypeConfiguration<Category>
{
public CategoryConfiguration()
{
ToTable("Categories");
HasKey(m => m.CategoryId);
}
}
public class PhoneConfiguration : EntityTypeConfiguration<Phone>
{
public PhoneConfiguration()
{
ToTable("Phones");
HasKey(m => m.ProductId);
}
}
Seed method:
protected override void Seed(BestPhone.Data.BestPhoneDbContext context)
{
context.Categories.AddOrUpdate(new Category(){Name = "Phones", CategoryId = 1});
...
//getting records from a csv file and holding them in an array.
var records = csvReader.GetRecords<Phone>().ToArray();
foreach (var record in records)
{
record.CategoryId = 1;
}
context.Phones.AddRange(records);
context.SaveChanges();
}
}
Try to add the next method on your CategoryConfiguration class:
public void Configure(EntityTypeBuilder<Category> builder)
{
builder
.HasMany(s => s.Products)
.WithOne(t => t.Category)
.HasForeignKey(t => t.CategoryId);
}
I'm not sure but it seems a system does not take into account your foreign key during seeding.
A very beginner question:
I have two classes, Review and ReviewSentences:
public class Review
{
public virtual int recordId { get; set; }
public virtual string reviewerId { get; set; }
public virtual string reviewerName { get; set; }
public virtual string country { get; set; }
public virtual string zipCode { get; set; }
public virtual string reviewProduct { get; set; }
public virtual string reviewText { get; set; }
public virtual string reviewTextLanguage { get; set; }
public virtual double sentimentScore { get; set; }
public virtual bool isScoreRefined { get; set; }
}
pulic class ReviewSentences
{
public virtual int recordId { get; set; }
public virtual int reviewId { get; set; }
public virtual int sentenceId { get; set; }
public virtual string sentence { get; set; }
public virtual double sentimentScore { get; set; }
}
The property ReviewSentences.reviewId is a foreign key referring to Review.recordId. One review can have many sentences (Review:ReviewSentences is 1:Many)
I have been trying for a long time now but unable to replicate the following query in terms of NHibernate with session.CreateCriteria:
select * from Reviews r
left join
ReviewSentences rs
on
r.RecordId = rs.ReviewId
where rs.ReviewId is null
The query gives me all reviews from the Review table that do not have any records in the ReviewSentences table.
It is a matter of mapping you should include an array of ReviewSentences in your Review class and map it correctly.
public class Review
{
public virtual int recordId { get; set; }
public virtual string reviewerId { get; set; }
public virtual string reviewerName { get; set; }
public virtual string country { get; set; }
public virtual string zipCode { get; set; }
public virtual string reviewProduct { get; set; }
public virtual string reviewText { get; set; }
public virtual string reviewTextLanguage { get; set; }
public virtual double sentimentScore { get; set; }
public virtual bool isScoreRefined { get; set; }
public virtual IList<ReviewSentences> sentences { get; set; }
}
pulic class ReviewSentences
{
public virtual int recordId { get; set; }
public virtual int reviewId { get; set; }
public virtual int sentenceId { get; set; }
public virtual string sentence { get; set; }
public virtual double sentimentScore { get; set; }
}
then in the mapping you should refer sentences as a reference.
but you did not said which kind of mapping your using (Fluent, conformist, etc.)
Fixed the mapping in hbm.xml files and got the required results using:
var reviews= session.CreateCriteria<Review>("r")
.CreateCriteria("r.sentences", JoinType.LeftOuterJoin)
.Add(Restrictions.IsNull("recordId"))
.List<Review>();
Here is my codes;
public List<SbtKlasorViewModel> GetFoldersWithIndexedDocuments()
{
//TODO - I can't find right query. We need folders with documents but only documents which be Indexed
using (ISession session = DatabaseProvider.SessionFactory.OpenSession())
{
List<DokumanlarModel> dokumanList = session.QueryOver<DokumanlarModel>()
.Where(x => x.IndexlenmeTarihi != null)
.List().ToList();
var list = dokumanList.GroupBy(x => x.Klasor.Aciklama);
List<SbtKlasorModel> folders = list as List<SbtKlasorModel>;
////Transforming SbtKlasorModel to SbtKlasorViewModel for respose
List<SbtKlasorViewModel> transformedFolders = folders
.Select(x => ModelTransformer.TransformModel(x)).ToList();
return transformedFolders;
}
}
DokumanlarModel.cs:
public class DokumanlarModel : SModuleClass
{
public virtual int DokumanId { get; set; }
public virtual string DokumanAdi { get; set; }
public virtual int DosyaBoyutu { get; set; }
public virtual int Durum { get; set; }
public virtual string EskiPath { get; set; }
public virtual string IndexTahsisKullanici { get; set; }
public virtual DateTime? IndexlenmeTarihi { get; set; }
public virtual string IndexleyenKullanici { get; set; }
public virtual string KaliteKontrolKullanici { get; set; }
public virtual DateTime? KaliteKontrolTarihi { get; set; }
public virtual SbtKlasorModel Klasor { get; set; }
public virtual int KlasordekiSira { get; set; }
public virtual DokNitelikTipModel NitelikTipId { get; set; }
public virtual int OcrDurum { get; set; }
public virtual string Path { get; set; }
public virtual int SayfaSayisi { get; set; }
public virtual DateTime? TaranmaTarihi { get; set; }
public virtual string TarayanKullanici { get; set; }
public virtual int Versiyon { get; set; }
public virtual string OrjinalPath { get; set; }
public virtual IList<LogDokumanModel> LogDokumanList { get; set; }
public virtual IList<DokumanlarOcrModel> DokumanlarOcrList { get; set; }
public virtual IList<DokVersiyonModel> DokVersiyonList { get; set; }
public virtual IList<DokMetaDataArsivModel> DokMetaDataArsivList { get; set; }
public DokumanlarModel()
{
LogDokumanList = new List<LogDokumanModel>();
DokumanlarOcrList = new List<DokumanlarOcrModel>();
DokVersiyonList = new List<DokVersiyonModel>();
DokMetaDataArsivList = new List<DokMetaDataArsivModel>();
}
}
SbtKlasorModel.cs:
public class SbtKlasorModel : SModuleClass
{
public virtual int KlasorId { get; set; }
public virtual string Aciklama { get; set; }
public virtual string Ada { get; set; }
public virtual string KisiAdSoyad { get; set; }
public virtual string Mahalle { get; set; }
public virtual string Parsel { get; set; }
public virtual string SerhAciklama { get; set; }
public virtual DateTime SerhBaslangicTarihi { get; set; }
public virtual DateTime SerhBitisTarihi { get; set; }
public virtual SbtKullaniciModel SerhKullanici { get; set; }
public virtual string Pafta { get; set; }
public virtual string KlasorNo { get; set; }
public virtual string SiraNo { get; set; }
public virtual string AciklamaYeni { get; set; }
public virtual IList<IlskGrupKlasorModel> IlskGrupKlasorList { get; set; }
public virtual IList<DokumanlarModel> DokumanlarList { get; set; }
public virtual IList<DokTaleplerModel> DokTaleplerList { get; set; }
public SbtKlasorModel()
{
IlskGrupKlasorList = new List<IlskGrupKlasorModel>();
DokumanlarList = new List<DokumanlarModel>();
DokTaleplerList = new List<DokTaleplerModel>();
}
}
I got data like List from database. And grouped by "DokumanlarModel.Klasor.Aciklama". But I need List list. I tried like above. It returns null. What should i do for this type change?
public List<SbtKlasorViewModel> GetFoldersWithIndexedDocuments()
{
using (var session = DatabaseProvider.SessionFactory.OpenSession())
{
var foldersContainingIndexedDocs = session.QueryOver<SbtKlasorModel>()
.JoinQueryOver<DokumanlarModel>(x => x.DokumanlarList)
.Where(doc => doc.IndexlenmeTarihi != null)
.List();
//Transforming SbtKlasorModel to SbtKlasorViewModel for respose
return folders.Select(ModelTransformer.TransformModel).ToList();
}
}
I have a one-to-many relationship setup. IT is working fine but now I am trying to use pdfsharp and I need some help with the navigation properties. Every Measurement has 4 pictures. Front, Back, Right, Left. I need to include all 4 pics in the pdf. I am unable to reach them with what i have now. I can return the list of pictures per measurement in a table. Just dont know how to change it for this to work as well.
public class Measurement
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
public DateTime? MeasurementDate { get; set; }
public decimal? BustMeasurement { get; set; }
public decimal? ChestMeasurement { get; set; }
public decimal? FAT { get; set; }
public string MeasurementUploadBy { get; set; }
public DateTime? MeasurementUploadDate { get; set; }
public DateTime? MeasurementEditDate { get; set; }
public string MeasurementEditBy { get; set; }
public int? ClientId { get; set; }
[ForeignKey("ClientId")]
public virtual Client Client { get; set; }
public virtual ICollection<Picture> Pictures { get; set; }
}
public class Picture
{
public int Id { get; set; }
public string PictureFrontUrl { get; set; }
public string PictureBackUrl { get; set; }
public string PictureRightSideUrl { get; set; }
public string PictureLeftSideUrl { get; set; }
public string PictureNote { get; set; }
public string PictureUploadBy { get; set; }
public DateTime? PictureUploadDate { get; set; }
public DateTime? PictureDate { get; set; }
public string ClientName { get; set; }
public string PictureType { get; set; }
public Guid MeasurementId { get; set; }
[ForeignKey("MeasurementId")]
public virtual Measurement Measurement { get; set; }
}
MeasurementApi
public Measurement GetMeasurement(Guid id)
{
using (var context = new ApplicationDbContext())
{
Measurement model = new Measurement();
model = context.Measurements
.Include(x => x.Pictures)
.FirstOrDefault(j => j.Id == id);
return model;
}
}
PDFSharp GEt Call
apiMeasurementController adapter = new apiMeasurementController();
Measurement model = new Measurement();
model = adapter.GetMeasurement(id);
If you want your Measurement to have 4 pictures, and not a colleciton of pictures you should have something like this:
public class Measurement
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
....
// Won't need these
// public virtual ICollection<Picture> Pictures { get; set; }
public virtual Picture LeftPicture { get; set; }
public virtual Picture TopPicture { get; set; }
public virtual Picture RightPicture { get; set; }
public virtual Picture BottomPicture { get; set; }
}
And your picture:
public class Picture
{
public int Id { get; set; }
// Don't need these 4 any more.
// public string PictureFrontUrl { get; set; }
// public string PictureBackUrl { get; set; }
// public string PictureRightSideUrl { get; set; }
// public string PictureLeftSideUrl { get; set; }
public string PictureUrl { get; set; }
public string PictureNote { get; set; }
public string PictureUploadBy { get; set; }
public DateTime? PictureUploadDate { get; set; }
public DateTime? PictureDate { get; set; }
public string ClientName { get; set; }
public string PictureType { get; set; }
public Guid MeasurementId { get; set; }
[ForeignKey("MeasurementId")]
public virtual Measurement Measurement { get; set; }
}
And in your API
public Measurement GetMeasurement(Guid id)
{
using (var context = new ApplicationDbContext())
{
Measurement model = new Measurement();
model = context.Measurements
.Include(x => x.LeftPicture)
.Include(x => x.TopPicture)
.Include(x => x.RightPicture)
.Include(x => x.BottomPicture)
.FirstOrDefault(j => j.Id == id);
return model;
}
}
These are my entities:
public class Subscription : BaseItem
{
public virtual DateTime DateStart { get; set; }
public virtual DateTime? DateEnd { get; set; }
public virtual int Status { get; set; }
public virtual Account Account { get; set; }
public virtual Theater Theater { get; set; }
public virtual Agent Agent { get; set; }
}
public class Account : BaseItem
{
public virtual string LegalName { get; set; }
public virtual string FirstName { get; set; }
public virtual string UrlName { get; set; }
public virtual string Address1 { get; set; }
public virtual string Address2 { get; set; }
public virtual string City { get; set; }
public virtual string State { get; set; }
public virtual string ZipCode { get; set; }
public virtual string Country { get; set; }
public virtual string Tel { get; set; }
public virtual string Tel2 { get; set; }
public virtual string Fax { get; set; }
public virtual string Mobile { get; set; }
public virtual string Email { get; set; }
public virtual string Website { get; set; }
public virtual int DefaultVatRate { get; set; }
public virtual bool Bankrupt { get; set; }
public virtual string ExternalId { get; set; }
public virtual bool DoNotContact { get; set; }
public virtual bool NotInterested { get; set; }
public virtual Group Group { get; set; }
public virtual IList<Header> Headers { get; set; }
public virtual IList<Note> Notes { get; set; }
public virtual IList<Order> Orders { get; set; }
public virtual IList<Subscription> Subscriptions { get; set; }
}
public class Order : BaseItem
{
public virtual int Number { get; set; }
public virtual DateTime Date { get; set; }
public virtual string Description { get; set; }
public virtual double Amount { get; set; }
public virtual string Attachment { get; set; }
public virtual string AttachmentFilename { get; set; }
public virtual string AttachmentMimetype { get; set; }
public virtual bool? PaidToTheater { get; set; }
public virtual DateTime? DatePaidToTheater { get; set; }
public virtual bool? CashinByTheater { get; set; }
public virtual Account Account { get; set; }
public virtual Theater Theater { get; set; }
public virtual Agent Agent { get; set; }
public virtual IList<Invoice> Invoices { get; set; }
public virtual IList<OrdersAttachment> OrdersAttachments { get; set; }
public virtual IList<OrdersDueDate> OrdersDueDates { get; set; }
public virtual Header Header { get; set; }
}
public class Invoice : BaseItem
{
public virtual int Number { get; set; }
public virtual DateTime Date { get; set; }
public virtual double Amount { get; set; }
public virtual double VatRate { get; set; }
public virtual bool IsDisabled { get; set; }
public virtual bool IsSendMail { get; set; }
public virtual Order Order { get; set; }
public virtual IList<InvoicesDueDate> InvoicesDueDates { get; set; }
public virtual IList<InvoicesPayment> InvoicesPayments { get; set; }
}
I have a method in my program that build a "query" in a string variable.
private string GenerateQuery(FilterSubscription filterSubscription)
{
if (filterSubscription.FilterByOrder)
return "Account.Orders.Any()";
if (filterSubscription.FilterByInvoice)
return "Account.Orders.Any(Invoices.Any())"; //here is my problem
}
This is the call to the method
string query = GenerateQuery(filterSubscription)
var count = Session.Linq<Subscription>().Where(query).Count();
If I need to extract all accounts that have at least one Order is all OK.
But if I need to extract all accounts that have at least one Invoice I don't know how.
If I wrote
var count = Session.Linq<Subscription>().Where(s=>s.Account.Orders.Any(o=>o.Invoices.Any())).Count();
it works but if I use the string variable it doesn't.
It looks like you should return a delegate from GenerateQuery instead - something like:
private Expression<Func<Subscription, bool>> GenerateQuery(FilterSubscription filterSubscription)
{
if (filterSubscription.FilterByOrder)
return s => s.Account.Orders.Any();
if (filterSubscription.FilterByInvoice)
return s => s.Account.Orders.Any(o => o.Invoices.Any());
}
Then just update the query variable to be implicitly typed:
var query = GenerateQuery(filterSubscription);