Get All data from two tables in .net 5 web api? - c#

Patient.cs //This is Patient Model Class
namespace HMS.Models
{
public class Patient
{
[Key]
public string Id { get; set; }
public string Name { get; set; }
public int age { get; set; }
public int Weight { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public string PhoneNo { get; set; }
public string Disease { get; set; }
[JsonIgnore]
public IList<DoctorPatient> DoctorPatients { get; set; }
public InPatient InPatients { get; set; }
public OutPatient OutPatients { get; set; }
}
}
InPatient.cs //This InPatient Model Class
namespace HMS.Models
{
public class InPatient
{
[ForeignKey("Patient")]
public string InPatientId { get; set; }
public string RoomNo { get; set; }
public DateTime DateOfAddmission { get; set; }
public DateTime DateOfDischarge { get; set; }
public int Advance { get; set; }
public string LabNo { get; set; }
public Patient Patient { get; set; }
}
}
Here Patient and InPatient Attribute have one-to-one relationship
ViewInPatient.cs
namespace HMS.Models
{
public class ViewInPatient
{
public string Name { get; set; }
public int age { get; set; }
public int Weight { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public string PhoneNo { get; set; }
public string Disease { get; set; }
public string RoomNo { get; set; }
public DateTime DateOfAddmission { get; set; }
public DateTime DateOfDischarge { get; set; }
public int Advance { get; set; }
public string LabNo { get; set; }
}
}
Here is my DbContext class
public class ApplicationDbContext:DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<DoctorPatient>()
.HasOne(x => x.Doctor)
.WithMany(dp => dp.DoctorPatients)
.HasForeignKey(di => di.DoctorId);
modelBuilder.Entity<DoctorPatient>()
.HasOne(y => y.Patient)
.WithMany(dp => dp.DoctorPatients)
.HasForeignKey(pi => pi.PatientId);
}
public DbSet<Patient> Patients { get; set; }
public DbSet<Doctor> Doctors { get; set; }
public DbSet<DoctorPatient> DoctorPatients { get; set; }
public DbSet<InPatient> InPatients { get; set; }
//public DbQuery<ViewInPatient> ViewInPatients { get; set; }
}
How to get all data of both Patients and InPatients Table like in ViewInPatient class? (I tried to create a view in sql server but in add table window it shows InPatient instead of InPatients and it return null value)

You can join both models in a Linq expression and return ViewInPatient list:
var ViewInPatient_set =
YourContext
.InPatients
.Select(i=> new ViewInPatient()
{
Name = i.Patient.Name,
// ...
RoomNo = i.RoomNo,
// ...
}
)
.ToList(); // <-- transform to list is optional

Related

Including foreign key values into a DTO for a single record

It's been a while since I have done this, but I know there is an easy way to do this that I have forgotten. Below I have a class designed to populate a single record of a data object. But I cannot get the values from another table (related by foreign key) to populate using the lambda statement because I am missing something (the two values being pulled in from another table below can be seen as dto.LeaseName and dto.CarName). How should I write the lambda for the object dm?
public StationUnloadingLogDTO GetSingleRecordforLog(int Id)
{
StationUnloadingLogDTO dto = new StationUnloadingLogDTO();
StationUnloadingLog dm = new StationUnloadingLog();
dm = entity.StationUnloadingLog
.Where(x => x.Id == Id)
.FirstOrDefault();
dto.Id = dm.Id;
dto.DateLogged = dm.DateLogged;
dto.DriverName = dm.DriverName;
dto.TruckNumber = dm.TruckNumber;
dto.CarName = dm.Carrier.CarName;
dto.CarrierId = dm.CarrierId;
dto.SpecificGravity = dm.SpecificGravity;
dto.LactMeterOpen = dm.LactMeterOpen;
dto.LactMeterClose = dm.LactMeterClose;
dto.EstimatedBarrels = dm.EstimatedBarrels;
dto.TicketNumber = dm.TicketNumber;
dto.LeaseNumber = dm.LeaseNumber;
dto.LeaseName = dm.Company.CmpName;
dto.StationId = dm.StationId;
return dto;
}
Here are the related data classes
namespace Data.Models
{
public partial class Company
{
public Company()
{
StationUnloadingLog = new HashSet<StationUnloadingLog>();
}
public string CmpId { get; set; }
public string CmpName { get; set; }
public string CmpAddress1 { get; set; }
public string CmpAddress2 { get; set; }
public int? CmpCity { get; set; }
public string CmpZip { get; set; }
public string CmpPrimaryphone { get; set; }
public ICollection<StationUnloadingLog> StationUnloadingLog { get; set; }
}
public class StationUnloadingLogDTO
{
public int Id { get; set; }
public DateTime? DateLogged { get; set; }
public string DriverName { get; set; }
public string TruckNumber { get; set; }
public string CarrierId { get; set; }
public string CarName { get; set; }
public decimal? SpecificGravity { get; set; }
public decimal? LactMeterOpen { get; set; }
public decimal? LactMeterClose { get; set; }
public int? EstimatedBarrels { get; set; }
public string TicketNumber { get; set; }
public string LeaseName { get; set; }
public string LeaseNumber { get; set; }
public string StationId { get; set; }
}
public partial class StationUnloadingLog
{
public int Id { get; set; }
public DateTime? DateLogged { get; set; }
public string DriverName { get; set; }
public string TruckNumber { get; set; }
public string CarrierId { get; set; }
public decimal? SpecificGravity { get; set; }
public decimal? LactMeterOpen { get; set; }
public decimal? LactMeterClose { get; set; }
public int? EstimatedBarrels { get; set; }
public string TicketNumber { get; set; }
public string LeaseNumber { get; set; }
public string StationId { get; set; }
public Carrier Carrier { get; set; }
public Company Company { get; set; }
public Tractorprofile Tractorprofile { get; set; }
}
public partial class Carrier
{
public Carrier()
{
StationUnloadingLog = new HashSet<StationUnloadingLog>();
}
public string CarId { get; set; }
public string CarName { get; set; }
public string CarAddress1 { get; set; }
public string CarAddress2 { get; set; }
public int? CtyCode { get; set; }
public string CarZip { get; set; }
public string CarContact { get; set; }
public ICollection<StationUnloadingLog> StationUnloadingLog { get; set; }
}
You should query for your record with child entities like this.
dm = DbSet<StationUnloadingLog>
.Where(x => x.Id == Id).Include(x => x.Carrrier)
.FirstOrDefault();

Entity Framework creates a new record per foreign key in another table while seeding

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.

Entity Framework adds non existing column to query

I am using EF6.1.3. I have 3 poco's pickbatch, order, orderline.
public class PickBatch
{
public int Id { get; set; }
public string Barcode { get; set; }
public byte Status { get; set; }
public string Picker { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
public List<Order> Orders { get; set; }
}
public class Boxes
{
public Order()
{
OrderLines = new List<OrderLines>();
}
public int Id { get; set; }
public int? PickBatchId { get; set; }
public string OrderType { get; set; }
public string OrderNumber { get; set; }
public string CustomerNumber { get; set; }
public byte Status { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
public List<OrderLine> OrderLines { get; set; }
}
public class OrderLines
{
public int Id { get; set; }
public string Article { get; set; }
public string ArticleDescription { get; set; }
public int QtyOrdered { get; set; }
public int QtyDelivered { get; set; }
public int OrderId { get; set; }
public byte Status { get; set; }
public string Picker { get; set; }
public string PickLocation { get; set; }
public string Sorting { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
}
Not all the properties match the column names in the tables. So on model creating i am fixing this.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<PickBatch>().ToTable("PickBatch");
modelBuilder.Entity<PickBatch>().HasKey(b => b.Id);
modelBuilder.Entity<PickBatch>().Property(b => b.Id).HasColumnName("PickBatchId");
modelBuilder.Entity<Order>().HasKey(b => b.Id);
modelBuilder.Entity<Order>().Property(b => b.Id).HasColumnName("OrderId");
modelBuilder.Entity<OrderLine>().HasKey(b => b.Id);
modelBuilder.Entity<OrderLine>().Property(o => .Id).HasColumnName("OrderLineId");
}
When retrieve the orderlines I get an execption: Invalid column name 'PickBatch_Id'. I don't understand why does EF want to add this property?

Invalid column name: "ColumnName#" with a suffix number

I have a table Users:
I am using Entity Framework 6 to make the type configuration
public class UsersMapping : EntityTypeConfiguration<Users>
{
public UsersMapping()
{
HasKey(t => t.UserID);
Property(t => t.UserID).IsRequired();
ToTable("Users", "dbo");
Property(t => t.Id).HasColumnName("UserID");
}
}
and this is the Users class:
public class Users : EntityBase
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public DateTime DateCreated { get; set; }
public byte[] Timestamp { get; set; }
public byte[] Password { get; set; }
public DateTime? DateActivated { get; set; }
public bool LockedOut { get; set; }
public string Address { get; set; }
public string City { get; set; }
public int? State { get; set; }
public string Zip { get; set; }
public string SecurityQuestion { get; set; }
public string SecurityAnswer { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public bool? ReportServiceAccount { get; set; }
public string CompanyName { get; set; }
public int? ILAC { get; set; }
public string BioFingerprint { get; set; }
public string Title { get; set; }
public string Squad { get; set; }
public byte[] SignatureFile { get; set; }
public byte? CETGroupID { get; set; }
public string TokenID { get; set; }
public int? Pin { get; set; }
public string RadioNr { get; set; }
}
public class EntityBase
{
public int Id { get; set; }
}
I am trying to set the Id field as primary because my repository pattern works using the field Id that is not present on this case in the table. But when I am trying to get the set of users I get this error:
The column name is invalid UserID1
The weird thing to me is the #1 that is at the end. What I am doing wrong?

Creating Entity Model with Cross Referencing Table

Here are my models:
public partial class NEWS
{
public NEWS()
{
}
[Key]
public int NEWSID { get; set; }
public string Title { get; set; }
public string Text { get; set; }
public string InsertDate { get; set; }
public int GroupingID { get; set; }
public virtual Subjects Subjects { get; set; }
}
public partial class Subjects
{
public Subjects()
{ this.NEWSs = new HashSet<NEWS>(); }
[Key]
public int GroupingID { get; set; }
public string Farsi { get; set; }
public string Latin { get; set; }
public virtual ICollection<NEWS> NEWSs { get; set; }
}
public class UserGroup
{
public UserGroup()
{ this.Userss = new HashSet<Users>(); }
[Key]
public int UserID { get; set; }
public string Title { get; set; }
public virtual ICollection<Users> Userss { get; set; }
}
public class Users
{
public Users()
{ }
public string Name { get; set; }
public string Family { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string PassWord { get; set; }
[Key]
public int UserID { get; set; }
public virtual UserGroup UserGroup { get; set; }
// public HashSet<Users> Userss { get; set; }
}
public class NEWSDBContext : DbContext
{
public NEWSDBContext()
: base()
{
Database.SetInitializer<NEWSDBContext>(null);
}
public DbSet<NEWS> NEWSs { get; set; }
public DbSet<Users> Userss { get; set; }
public DbSet<UserGroup> UserGroups { get; set; }
public DbSet<Subjects> Subjectss { get; set; }
}
I always get an error in return View(newss.ToList());:
The underlying provider failed on Open

Categories