I have a linq query below that can't find 'DateTimeScheduled'
var yogaSpace = (from u in context.YogaSpaces
orderby u.Address.LocationPoints.Distance(myLocation)
where ((u.Address.LocationPoints.Distance(myLocation) <= 8047) && (u.Events.DateTimeScheduled >= classDate))
select u).ToPagedList(page, 10);
DateTimeScheduled is red and intellisense can't find anything inside u.Events almost like it doesn't exist. Intellisnse doesn't see the members inside Events.
Here is my YogaSpace and YogaSpaceEvent objects. I can compile everything fine if I remove the clause "&& (u.Events.DateTimeScheduled >= classDate)", furthermore I have data in my table for this object that I seeded to use for testing!
public class YogaSpace
{
public int YogaSpaceId { get; set; }
[Index(IsUnique = false)]
[Required]
[MaxLength(128)]
public string ApplicationUserRefId { get; set; }
public virtual YogaSpaceOverview Overview { get; set; }
public virtual YogaSpaceDetails Details { get; set; }
public virtual ICollection<YogaSpaceImage> Images { get; set; }
[Required]
public ListingComplete ImageCompleted { get; set; }
public byte[] Thumbnail { get; set; }
public virtual YogaSpaceListing Listing { get; set; }
public virtual YogaSpaceAddress Address { get; set; }
public virtual ICollection<YogaSpaceReview> Reviews { get; set; }
[Required]
public DateTime DateCreated { get; set; }
public virtual ICollection<YogaSpaceEvent> Events { get; set; }
[Required]
[Index]
public YogaSpaceStatus Status { get; set; }
[Required]
[Range(0, 4)]
public int StepsToList { get; set; }
[ForeignKey("ApplicationUserRefId")]
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class YogaSpaceEvent
{
public int YogaSpaceEventId { get; set; }
//public string Title { get; set; }
[Index]
//research more about clustered indexes to see if it's really needed here
//[Index(IsClustered = true, IsUnique = false)]
public DateTime DateTimeScheduled { get; set; }
public int AppointmentLength { get; set; }
public int StatusEnum { get; set; }
[Index]
public int YogaSpaceRefId { get; set; }
[ForeignKey("YogaSpaceRefId")]
public virtual YogaSpace YogaSpace { get; set; }
}
The property u.Events is a collection of events. Therefore it cannot have a single value for DateTimeScheduled, it has multiple values.
You need to select events that have DateTimeScheduled >= classDate first. Something like this:
var yogaSpace = (from u in context.YogaSpaces
orderby u.Address.LocationPoints.Distance(myLocation)
where ((u.Address.LocationPoints.Distance(myLocation) <= 8047)
&& (u.Events.Any(e => e.DateTimeScheduled >= classDate)))
select u).ToPagedList(page, 10);
The changed portion of the code u.Events.Any(e => e.DateTimeScheduled >= classDate) will now return a boolean true or false that indicates if any of the events are scheduled on or after the class date.
Related
An exception occurred while reading a database value for property 'EMWH.UniqueAttchID'. The expected type was 'System.Nullable`1[System.Guid]' but the actual value was null.
I'm using EFCore 5.0 and I get the error listed above. If in my EMWH view I hide all records where there is a NULL in UniqueAttchID it works fine. But I can't seem to find a way to exclude the records where the principal key (for the relationship) is NULL. But still have the ability to view all records.
Code causing the error
var workOrder = await _context.EMWHs.AsNoTracking()
.Include(x => x.EMWIs).ThenInclude(x => x.HQATs)
.Where(x => x.KeyID == WorkOrderKeyId).SingleOrDefault();
EMWH
public class EMWH
{
public byte EMCo { get; set; }
public string WorkOrder { get; set; }
public string Equipment { get; set; }
public string? Description { get; set; }
public Guid? UniqueAttchID { get; set; }
[Column("udServiceRecordYN")]
public string? ServiceRecordYN { get; set; }
public char Complete { get; set; }
public long KeyID { get; set; }
[Column("DateSched")]
[Display(Name = "Scheduled Date")]
public DateTime ScheduledDate { get; set; }
public virtual EMEM EMEM { get; set; }
public virtual IEnumerable<EMWI> EMWIs { get; set; }
public virtual IEnumerable<HQAT> HQATs { get; set; }
}
HQAT
public class HQAT
{
public byte HQCo { get; set; }
public string FormName { get; set; }
public string KeyField { get; set; }
public string Description { get; set; }
public string AddedBy { get; set; }
public DateTime? AddDate { get; set; }
public string DocName { get; set; }
public int AttachmentID { get; set; }
public string TableName { get; set; }
public Guid? UniqueAttchID { get; set; }
public string OrigFileName { get; set; }
public string DocAttchYN { get; set; }
public string CurrentState { get; set; }
public int? AttachmentTypeID { get; set; }
public string IsEmail { get; set; }
public long KeyID { get; set; }
public virtual udEMCD EMCD { get; set; }
public virtual HQAF HQAF { get; set; }
public virtual EMWH EMWH { get; set; }
public virtual EMWI EMWI { get; set; }
public virtual udEMED EMED { get; set; }
}
DBContext
modelBuilder.Entity<EMWH>().ToTable("EMWH").HasKey(k=>new { k.EMCo, k.WorkOrder });
modelBuilder.Entity<HQAT>().HasOne(x => x.EMWH).WithMany(x => x.HQATs).HasForeignKey(x => x.UniqueAttchID)
.HasPrincipalKey(x => x.UniqueAttchID);
You have the relationship set up to count on public Guid? UniqueAttchID { get; set; } for keys between entities, but you have this set up as a nullable GUID type, so when the query runs the DB is likely coming across a null value in the table, and can't resolve the relationship. The simple solution and arguably best practice is to make those properties non-nullable, or define the relationship using int or long types as ID's, so they can't be null, and making sure your INSERT and UPDATE queries are properly setting the relationships. Either way, the null is where you should start and if you have records in the tables already that have null values you are expecting to use as keys, you could have some work on your hands to figure out how those are supposed to be linked and getting the nulls replaced with GUID values.
I have a statement in one of my entities which uses a foreign key to return an IEnumerable<CustomField>.
I have used LINQ in my repository to test the below method to see if it works and it does. But when I use the foreign key reference in the entity it returns null. Am I missing something here? How can I use a foreign key to gain access to the data in another entity.
Invoice entity:
[Table("vwinvoice")]
public class Invoice
{
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int Sys_InvoiceID { get; set; }
[DisplayName("Inc.In Turnover")]
public bool Turnover { get; set; }
public int FK_StatusID { get; set; }
[DisplayName("Invoice No.")]
public string InvoiceNumber { get; set; }
[DisplayName("Invoice Date")]
public DateTime InvoiceDate { get; set; }
[DisplayName("Document Type")]
public string DocType { get; set; }
[DisplayName("Supplier Invoice No.")]
[Column("SupplierInvoiceNumber")]
public string SuppInvNumber { get; set; }
public int FK_SupplierID { get; set; }
[DisplayName("Account Number")]
public string AccountNumber { get; set; }
[DisplayName("Order Number")]
public string OrderNumber { get; set; }
[DisplayName("Order Date")]
public DateTime? OrderDate { get; set; }
[DisplayName("Currency Code_Doc")]
public string CurrencyCode_Doc { get; set; }
[DisplayName("Net Amount_Doc")]
public decimal? NetAmount_Doc { get; set; }
[DisplayName("VAT Amount_Doc")]
public decimal? VATAmount_Doc { get; set; }
[DisplayName("Gross Amount_Doc")]
[Required]
public decimal? GrossAmount_Doc { get; set; }
[DisplayName("Currency Code_Home")]
public string CurrencyCode_Home { get; set; }
[DisplayName("Net Amount_Home")]
public decimal? NetAmount_Home { get; set; }
[DisplayName("VAT Amount_Home")]
public decimal? VATAmount_Home { get; set; }
[DisplayName("Gross Amount_Home")]
public decimal? GrossAmount_Home { get; set; }
[DisplayName("Payment Reference")]
public string PaymentReference { get; set; }
[DisplayName("Supplier")]
public string AccountName { get; set; }
[DisplayName("Status")]
public string StatusName { get; set; }
[DisplayName("Auditor Comments")]
public string AuditorComments { get; set; }
[DisplayName("Reviewer Comments")]
public string ReviewerComments { get; set; }
[DisplayName("Data Source")]
[Required]
public string DataOrigin { get; set; }
public int DetailLineCount { get; set; }
public IEnumerable<CustomField> ClientData {
get {
//Use the CustomFields foreign key to gain access to the data returns null.
return GetCustomFieldData(this.CustomFields.Select(r => r));
}
}
private IEnumerable<CustomField> GetCustomFieldData(IEnumerable<Entities.CustomFields> enumerable) {
return (from f in enumerable
select new CustomField {
Name = f.FK_CustomHeader,
Value = f.Value
});
}
//Custom Field Additions
public virtual ICollection<CustomFields> CustomFields { get; set; }
}
CustomFields entity:
[Table("tblCustomFields")]
public class CustomFields
{
[Key]
public int ID { get; set; }
public int? FK_SysInvoiceID { get; set; }
[StringLength(255)]
public string FK_CustomHeader { get; set; }
[StringLength(255)]
public string Value { get; set; }
public virtual Invoice Invoices { get; set; }
public virtual CustomFieldHeaders CustomFieldHeaders { get; set; }
}
I also cannot place a breakpoint in the get statement to see what happens, why is this? It just skips over the breakpoint whenever I try to return a list of Invoices, which can be seen here:
public IQueryable<Invoice> Invoices
{
get
{
var x = _ctx.Invoices.ToList();
return _ctx.Invoices;
}
}
You are using the virtual keyword when declaring your CustomFields property. As such it will be lazy loaded. If you want the property to be populated once returned from the repository you will need to explicitly Include the table in your method:
var x = _ctx.Invoices.Include(i => i.CustomFields).ToList();
return _ctx.Invoices;
Or you can remove the virtual keyword and the property will always be populated, with the consequent performance hit of the database join and the extra data being returned whenever you access Invoices.
I have a table that i am attempting to query in order to create a menu. I am also querying the related tables to pair down result. I have a models project that contains all of my data models. In my Entities file I have
public IDbSet<Agent> Agents { get; set; }
public IDbSet<UsersLogin> UsersLogins { get; set; }
public IDbSet<Role> Roles { get; set; }
public IDbSet<UserRoleMapping> UserRoleMappings { get; set; }
public IDbSet<Qualifier> Qualifiers { get; set; }
public IDbSet<tblMenus> tblMenu { get; set; }
public IDbSet<tblUserMenuMapping> tblUserMenuMappings { get; set; }
public IDbSet<tblRoleMenuMapping> tblRoleMenuMappings { get; set; }
In my Interface i have ICollection<tblMenus> GetAllMenus();
Then i have my linq query which pares everything down and returns main menus and child menus.
public ICollection<tblMenus> GetAllMenus()
{
if (Global.CurrentProfile.UserID == 1)
{
return DataAccess.tblMenu.Where(m => !m.IsDeleted).ToList();
}
else
{
var UserInfo = GetUserInfo();
UserType = UserInfo.First().UserTypeID;
var childRoleMenus =
from menus in DataAccess.tblMenu
join roleMenus in DataAccess.tblRoleMenuMappings on menus.MenuID equals roleMenus.MenuID
join userRoles in DataAccess.UserRoleMappings on roleMenus.RoleID equals userRoles.RoleID
where userRoles.UserID == Global.CurrentProfile.UserID && !menus.IsDeleted
select menus;
var userChildMenus =
from menus in DataAccess.tblMenu
join userMenus in DataAccess.tblUserMenuMappings on menus.MenuID equals userMenus.MenuID
where userMenus.UserID == Global.CurrentProfile.UserID
select menus;
var childMenus = childRoleMenus.Union(userChildMenus).ToList();
However when i execute the query in my page it returns this error.
The specified type member 'MenuID' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported
Here are my models.
public class tblMenus : ModelBase
{
public int MenuID { get; set; }
public string MenuName { get; set; }
public string MenuLink { get; set; }
public Nullable<int> ParentID { get; set; }
public Nullable<bool> IsParent { get; set; }
public string IconImagePath { get; set; }
public Nullable<int> ApplicationID { get; set; }
public int CreatedBy { get; set; }
public System.DateTime CreatedOn { get; set; }
public string UpdatedBy { get; set; }
public Nullable<System.DateTime> UpdatedOn { get; set; }
public bool IsDeleted { get; set; }
public string ProcessedPage { get; set; }
public string MenuTarget { get; set; }
public Nullable<bool> IsEnabled { get; set; }
public string MenuCategory { get; set; }
public int MenuOrder { get; set; }
public virtual ICollection<tblRoleMenuMapping> tblRoleMenuMapping { get; set; }
public int RoleMenuID { get; set; }
public int RoleID { get; set; }
public int MenuID { get; set; }
public int CreatedBy { get; set; }
public System.DateTime CreatedOn { get; set; }
public Nullable<int> UpdatedBy { get; set; }
public Nullable<System.DateTime> UpdatedOn { get; set; }
public Nullable<bool> IsDeleted { get; set; }
public string ProcessedPage { get; set; }
public string PageAccessibility { get; set; }
public virtual ICollection<tblMenus> tblMenus { get; set; }
public virtual ICollection<Role> Role { get; set; }
public class tblUserMenuMapping : ModelBase
{
public int UserMenuID { get; set; }
public int UserID { get; set; }
public int MenuID { get; set; }
public Nullable<int> CreatedBy { get; set; }
public Nullable<System.DateTime> CreatedOn { get; set; }
public Nullable<int> UpdatedBy { get; set; }
public Nullable<System.DateTime> UpdatedOn { get; set; }
public bool IsDeleted { get; set; }
It's hard to say for sure without seeing the whole of both model classes and your database. Some things to check are:
Verify each respective 'MenuID' column exist in each underlying table. Because you aren't using mapping configurations, you need to make sure the column names follow the convention naming EF expects.
Verify their is a foreign key relationship between the two tables.
From a more general perspective, I would consider using configuration classes so your relationships are explicit and your model is more easily changed from the tables they map to.
Finally, you may see some clues by inspecting the SQL that EF has generated. Use the technique described in this post for any red flags (like EF is looking for a column that doesn't exist):
var result = from x in appEntities
where x.id = 32
select x;
var sql = ((System.Data.Objects.ObjectQuery)result).ToTraceString();
What i am essentially trying to do is get all of the packages that have NOT been assigned a package location price for a specific location...
I have the following SQL:
SELECT * FROM Package
LEFT JOIN PackageLocationPrices ON Package.Id = PackageLocationPrices.PackageId
Where PackageLocationPrices.LocationId IS NULL
How can i convert this into Linq to entities?
I have tried something like this:
this.db.Packages.Include(p => p.PackageLocationPrices).Where(p => p.Id == p.PackageLocationPrices.????).ToList();
I am able to join package location prices but i am unable to get the properties of the packagelocationprices to do the SQL above? Below is my schema...The PackageLocationPrices.PackageId is a foreign key of Package.Id
Package Entitiy:
public partial class Package
{
public Package()
{
this.DiscountCodes = new HashSet<DiscountCode>();
this.PackageLocationPrices = new HashSet<PackageLocationPrice>();
this.Memberships = new HashSet<Membership>();
}
public int Id { get; set; }
public string Name { get; set; }
public int PackageOrder { get; set; }
public int PackageTypeId { get; set; }
public int PackagePeriodDays { get; set; }
public int PackagePeriodMonths { get; set; }
public int PackageSuspensionLimit { get; set; }
public int PackageSuspensionLimitIfAdminOverride { get; set; }
public int PackageSuspensionMinLength { get; set; }
public int PackageSuspensionMaxLength { get; set; }
public int PackageSuspensionsMaxLengthCombined { get; set; }
public int PackagePaymentHolidayLimit { get; set; }
public int PackagePaymentHolidayMinLength { get; set; }
public int PackagePaymentHolidayMaxLength { get; set; }
public int PackageVisitLimit { get; set; }
public bool PackageIsActive { get; set; }
public bool PackageIsReoccuring { get; set; }
public bool PackagePayInFull { get; set; }
public bool PackageIsSession { get; set; }
public System.DateTime CreatedDate { get; set; }
public System.DateTime ModifiedDate { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public virtual AspNetUser AspNetUserCreatedBy { get; set; }
public virtual AspNetUser AspNetUserModifiedBy { get; set; }
public virtual ICollection<DiscountCode> DiscountCodes { get; set; }
public virtual PackageType PackageType { get; set; }
public virtual ICollection<PackageLocationPrice> PackageLocationPrices { get; set; }
public virtual ICollection<Membership> Memberships { get; set; }
}
Package Location Price Entity:
public partial class PackageLocationPrice
{
public int Id { get; set; }
public int LocationId { get; set; }
public int PackageId { get; set; }
public decimal MonthlyPrice { get; set; }
public decimal TotalPrice { get; set; }
public System.DateTime CreatedDate { get; set; }
public System.DateTime ModifiedDate { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public virtual AspNetUser AspNetUserCreatedBy { get; set; }
public virtual AspNetUser AspNetUserModifiedBy { get; set; }
public virtual Location Location { get; set; }
public virtual Package Package { get; set; }
}
var result = (from p in Package
join q in PackageLocationPrices on p.Id equals q.PackageId into pq
from r in pq.DefaultIfEmpty()
select new {p, r}).ToList();
This should return something exactly like your SQL query.
I think you can create your query from another perspective:
var query=(from pl in db.PackageLocationPrices
where pl.LocationId == null
select pl.Package).ToList();
If you have disabled lazy loading then also need to use the Include extension method:
var query=(from pl in db.PackageLocationPrices.Include(p=>p.Package)
where pl.LocationId == null
select pl.Package).ToList();
Using method syntax would be this way:
var query=db.PackageLocationPrices.Include(p=>p.Package)
.Where(pl=>pl.LocationId == null)
.Select(pl=>pl.Package)
.ToList();
If you want as result both Package and PackageLocationPrice, then do this:
var query=db.PackageLocationPrices.Include(p=>p.Package)
.Where(pl=>pl.LocationId == null)
.ToList();
With this last query your are going to get a list of PackageLocationPrice, and if you want see the related Package for a givenPackageLocationPrice, you can use the Package navigation property.
I am using Microsoft SQL Server Managment Studio 2008. I am trying to get information from database. There are the example of linq query
var fbPost = db.FacebookStatusUpdates
.Where(f => f.Status == FacebookNotificationStatus.Active &&
f.Alarm.User.FbStatus == true)
.AsEnumerable()
.Where(f => f.FacebookUpdateTime - f.ClientTime.Offset <=
DateTimeOffset.Now.UtcDateTime.AddSeconds(f.Offset))
.ToList();
There is my stored procedure:
declare #date2 datetimeoffset=getutcDate();
select a.*
from [Alllarm].[dbo].[FacebookStatusUpdates] a
inner join [Alllarm].[dbo].[Alarms] b
inner join [Alllarm].[dbo].[Users] o
on o.[Id] = b.[User_id] on b.Id=a.[Alarm_id]
where o.[FbStatus] = 1 and a.Status=2
and DATEADD(hour,datepart(tz,a.ClientTime),a.FacebookUpdateTime)<=DATEADD(second, a.Offset, #date2);
Thare is my model:
public class User
{
public long Id { get; set; }
public string FacebookID { get; set; }
public string AccessToken { get; set; }
public DateTime UpdateTime { get; set; }
public bool? FbStatus { get; set; }
public virtual Device Device { get; set; }
public virtual List<Alarm> Alarms { get; set; }
public virtual List<Sms> Sms { get; set; }
}
public class Alarm
{
public long Id { get; set; }
public DateTime StartDate { get; set; }
public int Snoozes { get; set; }
public bool Repeat { get; set; }
public DateTime AlarmUpdateTime { get; set; }
public virtual User User { get; set; }
public virtual List<FacebookNotificationStatus> StatusUpdates { get; set; }
}
public class FacebookStatusUpdate
{
public long Id { get; set; }
public DateTime FacebookUpdateTime { get; set; }
public string PostId { get; set; }
public DateTime? FacebookPostTime { get; set; }
public DateTimeOffset ClientTime { get; set; }
public int Offset { get; set; }
public virtual FacebookNotificationStatus Status { get; set; }
public virtual Alarm Alarm { get; set; }
}
But when I ran a stored procedure nothing heppend. I think that I miss something in that line
and DATEADD(hour,datepart(tz,a.ClientTime),a.FacebookUpdateTime)<=DATEADD(second, a.Offset, #date2);
Can somebody help me ?
a.ClientTime has type DateTimeOffset 2013-11-13 12:03:36.0000000 +02:00
a.Offset type int (seconds)
Probem is there:
DATEADD(hour,datepart(tz,a.ClientTime),a.FacebookUpdateTime)
datepart(tz,a.ClientTime) return offset in minutes, so I change to
DATEADD(minute,datepart(tz,a.ClientTime),a.FacebookUpdateTime)
2013-11-13 12:03:36.0000000 +02:00 datepart return 120.