Entity Framework Linq Entity convert to CustomModel - entity-framework

I have the following linq to entity:
var dbShifts = DbContext.Set < SetupShift > ()
.AsNoTracking()
.Where(s => s.ShiftCode == shiftCode).ToList();
The Entity SetupShift has the following properties:
public class SetupShift
{
public int ShiftId { get; set; }
public string ShiftCode { get; set; }
public byte Day { get; set; }
public TimeSpan InTime { get; set; }
public TimeSpan OutTime { get; set; }
public int WorkHours { get; set; }
public TimeSpan LunchOut { get; set; }
public TimeSpan LunchIn { get; set; }
public bool IsActive { get; set; }
public string CategoryType { get; set; }
}
Now, I need to wrap it to a custom model ShiftModel:
public class ShiftModel
{
public int ShiftId { get; set; }
public string ShiftCode { get; set; }
public byte Day { get; set; }
public string DayName { get; set; }
public string InTime { get; set; }
public string OutTime { get; set; }
public int WorkHours { get; set; }
public string LunchOut { get; set; }
public string LunchIn { get; set; }
public bool IsActive { get; set; }
public string CategoryType { get; set; }
}
The only difference between the EF Entity model and my ShiftModel is that the TimeSpan properties are String in the Custom model.
I would like to know if there is a fast way to generate my ShiftModel from my Entity data instead of looping every entity:
List<ShiftModel> shifts = new List<ShiftModel>();
foreach(var entity in SetupShift){
....
newShiftModel = new ShiftModel();
newShiftModel.InTime = new TimeSpan(0, 0, 0).ToString(#"hh\:mm");
....
....
shifts.Add(newShiftModel);
}

You could do something like
var dbShifts = DbContext.Set < SetupShift > () .AsNoTracking() .Where(s => s.ShiftCode == shiftCode).Select(x => new ShiftModel() {
ShiftId = x.ShiftId,
ShiftCode = x.ShiftCode,
Etc.....
}).ToList();
Apologies for the poor formatting answering this from my phone.

Related

EF-Core query but value missing, even it show in database

here is the simple query code...
var order = await _context.ProductOrders
.FirstOrDefaultAsync(x => x.Id == orderId.ToInt());
This is the entity of ProdictOrders
public class ProductOrder
{
public int Id { get; set; }
public int MovieTicketEnrollmentId { get; set; }
public string ProductOrderStatusCode { get; set; }
public int? InvoiceId { get; set; }
public DateTime CreateDate { get; set; }
public string CreateBy { get; set; }
public DateTime? UpdateDate { get; set; }
public string UpdateBy { get; set; }
/**
* Navigation Property
*/
public MovieTicketEnrollment MovieTicketEnrollment { get; set; }
public ProductOrderStatus ProductOrderStatus { get; set; }
public ICollection<ProductOrderItem> ProductOrderItems { get; set; }
public Invoice Invoice { get; set; }
}
This data in the database
And what I got after executing query command above... what's just happening here?
MovieTicketEnrollmentId should equal to 1

EF Lambda How to make projection for GroupJoin

I am trying to query EF models. (GameBank and GameCouponBank) How can I make a projection for left outer join (GoupJoin)?
Can I make projection for Coupons?
Here is my query
var gameBankResult = context.GameBanks.GroupJoin(context.GameCouponBanks, g => g.GameBankID, gc => gc.GameBankID,
(g,gc) => new {
g.quantity,
g.currency,
g.initiationResultCode,
g.productCode,
g.productDescription,
g.referenceId,
g.responseDateTime,
g.unitPrice,
g.totalPrice,
Coupons = gc
})
.Where(g => g.productCode == initiate.productCode)
.Select(s => s);
Here is models:
public class GameBank
{
public int GameBankID { get; set; }
public string referenceId { get; set; }
public string productCode { get; set; }
public int quantity { get; set; }
public string version { get; set; }
public DateTime? requestDateTime { get; set; } = DateTime.Now;
public int? customerID { get; set; }
public string password { get; set; }
public DateTime? responseDateTime { get; set; } = DateTime.Now;
public string initiationResultCode { get; set; }
public string companyToken { get; set; }
public int used { get; set; }
public string productDescription { get; set; }
public string currency { get; set; }
public double unitPrice { get; set; }
public double totalPrice { get; set; }
public virtual List<GameCouponBank> coupons { get; set; }
}
public class GameCouponBank
{
public int Id { get; set; }
public int GameBankID { get; set; }
public DateTime? expiryDate { get; set; }
public string Serial { get; set; }
public string Pin { get; set; }
}
You don't need to use GroupJoin explicitly. You can simply project your query as follows:
var gameBankResult = context.GameBanks.Where(g => g.productCode == initiate.productCode)
.Select(g => new {
g.quantity,
g.currency,
g.initiationResultCode,
g.productCode,
g.productDescription,
g.referenceId,
g.responseDateTime,
g.unitPrice,
g.totalPrice,
Coupons = g.coupons.Select(c => new {c.Id, c.GameBankID,...}).ToList() //<-- Here is the projection for coupons
}).FirstOrDefault(); // I assume you are returning single entity, if not then use `.ToList()` instead of `.FirstOrDefault()`

EF Core Returns one Record where Many are Expected when Using Foreign Key Relationship

I have a database that stores data regarding Facilities, Doctors, and revenue for both of the previous items - FacilityRevenue and DoctorRevenue. There are also FaciltyMaster and DoctorMaster tables that have a one to many relationship with the FacilityRevenue and DoctorRevenue tables. That is, one doctor or facility master record is related to many DoctorId or FacilityId records in the FacilityRevenue and DoctorRevenue tables. I've attempted to place foreign key relationships so that DoctorId on DoctorRevenue relates to DoctorId on DoctorMaster and FacilityId on FacilityRevenue relates to FacilityId on FaclityMaster. However, I'm not confident that Entity Framework is reading this as such.
The model for each is as follows:
public partial class FacilityMaster
{
public FacilityMaster()
{
DoctorRevenue = new HashSet<DoctorRevenue>();
FacilityRevenue = new HashSet<FacilityRevenue>();
}
[Key]
public int FacilityId { get; set; }
public string FacilityName { get; set; }
public virtual ICollection<DoctorRevenue> DoctorRevenue { get; set; }
public virtual ICollection<FacilityRevenue> FacilityRevenue { get; set; }
}
public partial class DoctorMaster
{
public DoctorMaster()
{
DoctorRevenue = new HashSet<DoctorRevenue>();
}
[Key]
public int DoctorId { get; set; }
public string DoctorName { get; set; }
public string DoctorSpecialty { get; set; }
public virtual ICollection<DoctorRevenue> DoctorRevenue { get; set; }
}
public partial class DoctorRevenue
{
[Key]
public int RecordId { get; set; }
public int DoctorId { get; set; }
public int FacilityId { get; set; }
public string FacilityName { get; set; }
public string DoctorName { get; set; }
public DateTime? Date { get; set; }
public decimal? DoctorInvoices { get; set; }
public decimal? TotalRevenue { get; set; }
public virtual DoctorMaster Doctor { get; set; }
public virtual FacilityMaster Facility { get; set; }
}
public partial class FacilityRevenue
{
[Key]
public int RecordId { get; set; }
public int FacilityId { get; set; }
public string FacilityName { get; set; }
public DateTime Date { get; set; }
public decimal? TotalInvoices { get; set; }
public decimal? TotalRevenue { get; set; }
public virtual FacilityMaster Facility { get; set; }
}
I have configured, in part, my FacilityRevenueRepository as follows:
public IEnumerable<FacilityRevenue> GetFacRevenues(Int32 pageSize, Int32 pageNumber, String name)
{
var query = _context
.Set<FacilityRevenue>()
.AsQueryable()
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
if (!String.IsNullOrEmpty(name))
{
query = query.Where(item => item.FacilityName.Contains(name));
}
return query;
}
The relevant portion of my FacilityRevenueController is as follows:
[HttpGet]
[Route("GetFacilityRevenues")]
public async Task<IActionResult> GetFacilityRevenues(Int32? pageSize = 10, Int32? pageNumber = 1, String FacilityName = null)
{
var response = new ListModelResponse<FacRevViewModel>() as IListModelResponse<FacRevViewModel>;
try
{
response.PageSize = (Int32)pageSize;
response.PageNumber = (Int32)pageNumber;
response.Model = await Task.Run(() =>
{
return FacilityRevenueRepository
.GetFacRevenues(response.PageNumber, response.PageSize, FacilityName)
.Select(item => item.ToViewModel())
.ToList();
});
response.Message = String.Format("Total Records {0}", response.Model.Count());
}
catch (Exception ex)
{
response.DidError = true;
response.ErrorMessage = ex.Message;
}
return response.ToHttpResponse();
}
The DbContext is as follows:
public partial class ERPWAGDbContext : DbContext
{
public ERPWAGDbContext(DbContextOptions<ERPWAGDbContext> options)
:base(options)
{ }
public DbSet<DoctorMaster> Doctors { get; set; }
public DbSet<FacilityMaster> Facilities { get; set; }
public DbSet<DoctorRevenue> DoctorRevenue { get; set; }
public DbSet<FacilityRevenue> FacilityRevenue { get; set; }
}
When I run this using dotnet run, Postman returns just one record for GetFacilityRevenues, where several hundred are expected.
How do I ensure that all records for a given facility are returned, and likewise for doctors, when my GetFacilities and GetDoctors API methods are called?

Complex subquery in Entity Framework 6

I have an entity called Insurance like this:
public class Insurance : BaseEntity, IExpirationDocument
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public override int Id { get; set; }
[Column(TypeName = "NVARCHAR")]
[StringLength(256)]
public string PathToCertificate { get; set; }
[Column(TypeName = "NVARCHAR")]
[StringLength(50)]
public string Filename { get; set; }
public int Value { get; set; }
public string Name => InsuranceType.Name;
public DateTime ExpiryDate { get; set; }
public DateTime IssueDate { get; set; }
public bool Active { get; set; }
public int InsuranceTypeId { get; set; }
public virtual InsuranceType InsuranceType { get; set; }
public int InsurerId { get; set; }
public virtual Insurer Insurer { get; set; }
public int ApplicantId { get; set; }
public virtual Applicant Applicant { get; set; }
public int? DocumentEmailHistoryId { get; set; }
public virtual DocumentEmailHistory DocumentEmailHistory { get; set; }
public Insurance()
{
Active = true;
}
}
Would it be possible to do this type of query with Entity Framework:
SELECT *
FROM Insurances i1
INNER JOIN
(SELECT
insuranceTypeId, applicantid, MAX(IssueDate) as 'maxissuedate'
FROM
Insurances
GROUP BY
insuranceTypeId, applicantid) AS i2 ON i1.applicantid = i2.applicantid
AND i1.insuranceTypeId = i2.insuranceTypeId
WHERE
i1.issueDate = i2.maxissuedate
If you are trying to get latest issued Insurance according to InsuranceTypeId and ApplicantId you can group data according to needed properties, order by IssueDate descendingly and take only one Insurance info. Of course it will not give you the same query but it will give you the same result:
var result = context.Insurances
.GroupBy(m => new { m.InsuranceTypeId , m.ApplicantId })
.Select( g => new
{
MaxInsurance = g.OrderByDescending(m => m.IssueDate)
.Take(1)
})
.SelectMany(m => m.MaxInsurance);

Getting ObjectContext error even after calling ToList

When calling the method directly below I get a ObjectDisposedException when calling Mapper.Map with the retrieved list.
System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
public IEnumerable<Models.Provider> Get(string owner)
{
List<Data.Models.Provider> providers;
using (var db = new Data.ProviderDirectoryContext())
{
providers = db.Providers.Where(p => p.Owner.Name == owner).ToList();
}
var dtoProviders = Mapper.Map<List<Data.Models.Provider>, List<Models.Provider>>(providers);
return dtoProviders;
}
I previously had the code like this (below), I wasn't getting an error, but the database was getting pounded when doing the mapping, and it was taking too long. I don't want to hit the database, when doing the mapping.
public IEnumerable<Models.Provider> Get(string owner)
{
using (var db = new Data.ProviderDirectoryContext())
{
var providers = db.Providers.Where(p => p.Owner.Name == owner).ToList();
var dtoProviders = Mapper.Map<List<Data.Models.Provider>, List<Models.Provider>>(providers);
return dtoProviders;
}
}
How can I retrieve all the data before doing the mapping?
Here is the DbContext and the Data.Models.Provider for your reference.
public class ProviderDirectoryContext : DbContext
{
public DbSet<Owner> Owners { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<LocationAuditLog> LocationAuditLog { get; set; }
public DbSet<Office> Offices { get; set; }
public DbSet<OfficePhoneNumber> OfficePhoneNumbers { get; set; }
public DbSet<OfficeAuditLog> OfficeAuditLog { get; set; }
public DbSet<OfficeDay> OfficeDays { get; set; }
public DbSet<Provider> Providers { get; set; }
public DbSet<ProviderPhoneNumber> ProviderPhoneNumbers { get; set; }
public DbSet<ProviderAuditLog> ProviderAuditLog { get; set; }
public DbSet<ProviderType> ProviderTypes { get; set; }
public DbSet<ProviderSpecialty> ProviderSpecialties { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Provider>().HasRequired(cn => cn.Owner).WithMany().WillCascadeOnDelete(false);
modelBuilder.Entity<Office>().HasRequired(cn => cn.Owner).WithMany().WillCascadeOnDelete(false);
}
}
public class Provider
{
public int Id { get; set; }
public int OwnerId { get; set; }
public virtual Owner Owner { get; set; }
public int? ProviderTypeId { get; set; }
public virtual ProviderType ProviderType { get; set; }
public int? ProviderSpecialtyId { get; set; }
public virtual ProviderSpecialty ProviderSpecialty { get; set; }
[Required]
[StringLength(75)]
public string FirstName { get; set; }
[StringLength(75)]
public string MiddleName { get; set; }
[Required]
[StringLength(75)]
public string LastName { get; set; }
[StringLength(100)]
public string EmailAddress { get; set; }
public virtual ICollection<ProviderPhoneNumber> PhoneNumbers { get; set; }
public string Note { get; set; }
public DateTime? InactiveOn { get; set; }
public int OfficeId { get; set; }
public virtual Office Office { get; set; }
public virtual ICollection<ProviderAuditLog> AuditLog { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
[Required]
[StringLength(75)]
public string CreatedBy { get; set; }
[Required]
public DateTime ModifiedOn { get; set; }
[Required]
[StringLength(75)]
public string ModifiedBy { get; set; }
}
Thanks for the help!
The problem is that the Models.Provider class contains other classes like Models.Office, and Models.PhoneNumbers that were not eagerly loaded by the query. In addition to that, the Models.Provider class needs to be flattened. The Mapper wants to recursively map everything, and it keeps going down to the next class. For example, Provider.Office.Location.Offices.
The solution is to flatten Models.Provider and add .Include() to the query so it eagerly loads the data required.
I'll clean this up a bit more, but this is currently working.
public IEnumerable<Models.Provider> Get(string owner)
{
List<Data.Models.Provider> providers;
using (var db = new Data.ProviderDirectoryContext())
{
providers = db.Providers
.Where(p => p.Owner.Name == owner)
.Include("ProviderType")
.Include("ProviderSpecialty")
.Include("Office")
.Include("PhoneNumbers")
.ToList();
}
var dtoProviders = Mapper.Map<List<Data.Models.Provider>, List<Models.Provider>>(providers);
return dtoProviders;
}
public class Provider
{
public int Id { get; set; }
public int OwnerId { get; set; }
public int OfficeId { get; set; }
public string OfficeName { get; set; }
public int? ProviderTypeId { get; set; }
public string ProviderTypeName { get; set; }
public int? ProviderSpecialtyId { get; set; }
public string ProviderSpecialtyName { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public virtual ICollection<PhoneNumber> PhoneNumbers { get; set; }
public string Note { get; set; }
public DateTime? InactiveOn { get; set; }
public DateTime CreatedOn { get; set; }
public string CreatedBy { get; set; }
public DateTime ModifiedOn { get; set; }
public string ModifiedBy { get; set; }
}
I am not sure how much this will help with performance but declaring the variable you don't want to dispose outside the using statement should fix your dispose exception.
public IEnumerable<Models.Provider> Get(string owner)
{
IEnumerable<Models.Provider> dtoProviders;
using (var db = new Data.ProviderDirectoryContext())
{
List<Data.Models.Provider> providers = db.Providers.Where(p => p.Owner.Name == owner).ToList();
dtoProviders = Mapper.Map<List<Data.Models.Provider>, List<Models.Provider>>(providers);
}
return dtoProviders;
}