Performance issue in entity framework - mysql

I have some DB models:
public class SomeEntity
{
[Key]
public int Id { get; set; }
public Schedule Schedule { get; set; }
public ICollection<Address> Addresses { get; set; }
public ICollection<Phone> Phones { get; set; }
public ICollection<Email> Emails { get; set; }
}
and
public class Schedule
{
[Key]
public int id { get; set; }
public ICollection<TimeRange> Monday { get; set; }
public ICollection<TimeRange> Tuesday { get; set; }
public ICollection<TimeRange> Wednesday { get; set; }
public ICollection<TimeRange> Thursday { get; set; }
public ICollection<TimeRange> Friday { get; set; }
public ICollection<TimeRange> Saturday { get; set; }
public ICollection<TimeRange> Sunday { get; set; }
}
And when I run:
var entity = _dbContext.SomeEntity
.Include(p => p.Addresses)
.Include(p => p.Emails)
.Include(p => p.Phones)
.Include(p => p.Schedule)
.ThenInclude(s => s.Monday)
.Include(p => p.Schedule)
.ThenInclude(s => s.Tuesday)
.Include(p => p.Schedule)
.ThenInclude(s => s.Wednesday)
.Include(p => p.Schedule)
.ThenInclude(s => s.Thursday)
.Include(p => p.Schedule)
.ThenInclude(s => s.Friday)
.Include(p => p.Schedule)
.ThenInclude(s => s.Saturday)
.Include(p => p.Schedule)
.ThenInclude(s => s.Sunday)
return entity;
It tooks a very long time to execute. How can I fix this?

You have way too many includes. There is currently no option to optimize it directly (include with filters will be in next version of ef core 2.1). If you really need all that data, you should use rawquery.

Related

I want to Add a foreignkey for a table using onModelCreating method in asp.net core

I created two tables named 'patient' and 'Admission'.For do that i created patient model and admission model classes.then i use HospitalDbContext class for creating tables using onModelCreating method. I want to use PatientId as a foreign-key of Admission table.But i can't find a way to add foreign key.Help me to solve this problem
Patient.cs :
public class Patient
{
public int PatientId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Nic { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public DateTime RegisterDate { get; set; }
public string CurrentState { get; set; }
public string Password { get; set; }
}
Admission.cs :
public class Admission
{
public int AdmissionId { get; set; }
public int PatientId { get; set; }
public DateTime AdmissionDate { get; set; }
public string reason { get; set; }
}
HospitalDbContext.cs :
public class HospitalDbContext : DbContext
{
public HospitalDbContext(DbContextOptions<HospitalDbContext> options)
: base(options)
{
}
public DbSet<Patient> Patients { get; set; }
public DbSet<Admission> Admissions { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Patient>(entity =>
{
entity.HasKey(e => e.PatientId);
entity.Property(e => e.FirstName);
entity.Property(e => e.LastName);
entity.Property(e => e.Nic);
entity.Property(e => e.Age);
entity.Property(e => e.Address);
entity.Property(e => e.Email);
entity.Property(e => e.Mobile);
entity.Property(e => e.RegisterDate);
entity.Property(e => e.CurrentState);
entity.Property(e => e.Password);
});
modelBuilder.Entity<Admission>(entity=>
{
entity.HasKey(e => e.AdmissionId);
entity.Property(e => e.PatientId);
entity.Property(e => e.AdmissionDate);
entity.Property(e => e.reason);
});
}
public DbSet<patient_information_system_api.Models.Admission> Admission { get; set; }
}
As far as I know, we couldn't directly create the relationship without modifying the your Patient and Admission class.
If you want to achieve one to one relationship between the Admission and Patient, you should add Admission and Patient as property in each class and then use entity.HasOne(x=>x.Patient).WithOne(x=>x.Admission).HasForeignKey("PatientId"); to achieve your requirement.
More details, you could refer to below codes:
public class Patient
{
public int PatientId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Nic { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public DateTime RegisterDate { get; set; }
public string CurrentState { get; set; }
public string Password { get; set; }
public Admission Admission { get; set; }
}
Admission:
public class Admission
{
public int AdmissionId { get; set; }
public int PatientId { get; set; }
public DateTime AdmissionDate { get; set; }
public string reason { get; set; }
public Patient Patient{ get; set; }
}
OnModelCreating:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Patient>(entity =>
{
entity.HasKey(e => e.PatientId);
entity.Property(e => e.FirstName);
entity.Property(e => e.LastName);
entity.Property(e => e.Nic);
entity.Property(e => e.Age);
entity.Property(e => e.Address);
entity.Property(e => e.Email);
entity.Property(e => e.Mobile);
entity.Property(e => e.RegisterDate);
entity.Property(e => e.CurrentState);
entity.Property(e => e.Password);
});
modelBuilder.Entity<Admission>(entity =>
{
entity.HasKey(e => e.AdmissionId);
entity.Property(e => e.PatientId);
entity.Property(e => e.AdmissionDate);
entity.Property(e => e.reason);
entity.HasOne(x=>x.Patient).WithOne(x=>x.Admission).HasForeignKey("PatientId");
});
}
You don't need to create foreign key there, just go to the Model that
you need to add foreign key on it and make a virtual from from the
model class that you need:
In your case, you can apply it like this:
public class Admission
{
public int AdmissionId { get; set; }
public int PatientId { get; set; }
[ScaffoldColumn(false)] //Add this to avoid create foreign key when scaffolding
public virtual Patient Patient {get; set;} //Add this to work as foreign key
public DateTime AdmissionDate { get; set; }
public string reason { get; set; }
}
After that when you need to read the foreign key, you can read it easily as follow:
//.Include used to read the foreign key
var _admission = await db.admission.Include(a => a.Patient).OrderBy(x => x.AdmissionDate);
And you can read more about foreign key and relationships from this link:
https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key

ASP .NET Core 2.1 Identity: UserRoles is null

In my Razor web app, I've tried to get a list of users and their roles the following ways:
_userManager.GetUsersInRoleAsync(role).Result;
_dbContext.Users.Include(u => u.UserRoles).ThenInclude(u => u.Role);
_userManager.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role).ToList();
And UserRoles is always null. Any idea what I'm doing wrong?
Here is my Startup:
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
Here is my model:
public class ApplicationUser : IdentityUser
{
public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }
}
public class ApplicationRole : IdentityRole
{
public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }
}
public class ApplicationUserRole : IdentityUserRole<string>
{
public virtual ApplicationUser User { get; set; }
public virtual ApplicationRole Role { get; set; }
}
Here is my OnModelCreating:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<ApplicationUser>(au =>
{
au.HasMany(e => e.UserRoles).WithOne(e => e.User).HasForeignKey(ur => ur.UserId).IsRequired();
});
builder.Entity<ApplicationRole>(ar =>
{
ar.HasMany(e => e.UserRoles).WithOne(e => e.Role).HasForeignKey(ur => ur.RoleId).IsRequired();
});
builder.Entity<ApplicationUserRole>(aur =>
{
aur.HasOne(ur => ur.Role).WithMany(r => r.UserRoles).HasForeignKey(ur => ur.RoleId).IsRequired();
aur.HasOne(ur => ur.User).WithMany(r => r.UserRoles).HasForeignKey(ur => ur.UserId).IsRequired();
});
}

Entity FrameWork lazy loading 0 to many fluent api mapping issue

I been breaking my head for hours trying to find out why my navigation property is coming back null for 0 to many scenario. For 1 to 1 it works just fine.
These are my entities:
public class Barber: BaseEntity
{
public string Street1 { get; set; }
public string Street2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public int? AppointmentId { get; set; }
public int? UserId { get; set; }
public virtual ICollection<Users> Users { get; set; }
public Barber()
{
}
}
public class Users: BaseEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public bool IsBarber { get; set; }
public int? BarberId { get; set; }
public string FacebookToken { get; set; }
public DateTime? CreatedOn { get; set;}
public virtual Barber Barber { get; set; }
/// <summary>
/// default constructor
/// </summary>
public Users() { }
}
my mapping is as follow:
for Barber:
public BarberMapping()
{
ToTable("Barber");
HasKey(p => p.Id);
Property(p => p.Street1).HasColumnName("Street1");
Property(p => p.Street2).HasColumnName("Street2");
Property(p => p.City).HasColumnName("City");
Property(p => p.State).HasColumnName("State");
Property(p => p.PostalCode).HasColumnName("PostalCode");
Property(p => p.AppointmentId).HasColumnName("AppointmentId");
Property(p => p.UserId).HasColumnName("UserId");
HasOptional(p => p.Users)
.WithMany()
.HasForeignKey(p => p.UserId);
}
}
for User:
public UserMapping()
{
ToTable("Users");
HasKey(p => p.Id);
Property(p => p.FirstName);
Property(p => p.LastName );
Property(p => p.Password);
Property(p => p.Email);
Property(p => p.CreatedOn);
Property(p => p.FacebookToken);
Property(p => p.IsBarber);
}
Finally i'm calling my data like this:
_userRepository.All.Where(p => p.Id == id).Include(p => p.Barber).FirstOrDefault();
When the query comes back I get everything except the Barber property which comes back as null. Anything i'm missing to make this relationShip work?
I'm using EF 6.1.3 with mySQL 6.9 on visual studio for mac.

Entity Framewrok 5 fluent mapping for many to many with 3 entities

I have the following scenario that is giving me a hard time:
public class SegUser
{
public string IdUser { get; set; }
public List<SegRol> SegRoles { get; set; }
public virtual List<SegApps> Apps{ get; set; }
}
public class SegRole
{
public virtual int IdRole { get; set; }
public virtual List<SegUer> SegUsers { get; set; }
public virtual List<SegApp> Apps { get; set; }
}
public class SegApp
{
public virtual int IdApp{ get; set; }
public virtual List<SegUser> Users { get; set; }
public virtual List<SegRole> Roles { get; set; }
}
In my database I have those 3 tables and an extra table with 3 PKs (one for each entity) to establish the relationship between those 3 entities.
How can I achieve the mapping with Entity Framework 5 fluent API.
I've already tried:
private void MapSegUser()
{
//mapping of another fields
entityConfiguration
.HasMany(x => x.SegRoles)
.WithMany(x => x.SegUsers)
.Map(mc =>
{
mc.MapLeftKey("id_role");
mc.MapRightKey("id_user");
mc.ToTable("seg_users_roles");
});
entityConfiguration
.HasMany(x => x.Apps)
.WithMany(x => x.Users)
.Map(mc =>
{
mc.MapLeftKey("id_app");
mc.MapRightKey("id_user");
mc.ToTable("seg_users_roles_apps");
});
}
private void MapSegApp()
{
//mapping of another fields
entityConfiguration
.HasMany(x => x.Users)
.WithMany(x => x.Apps)
.Map(mc =>
{
mc.MapLeftKey("id_user");
mc.MapRightKey("id_app");
mc.ToTable("seg_users_roles_apps");
});
}
private void MapSegRole()
{
//mapping of another fields
entityConfiguration
.HasMany(x => x.SegUsers)
.WithMany(x => x.SegRoles)
.Map(mc =>
{
mc.MapLeftKey("id_user");
mc.MapRightKey("id_role");
mc.ToTable("seg_users_roles");
});
}

NHibernate and MySql is inserting and Selecting, not updating

Something strange is going on with NHibernate for me. I can select, and I can insert. But I can't do and update against MySql.
Here is my domain class
public class UserAccount
{
public virtual int Id { get; set; }
public virtual string UserName { get; set; }
public virtual string Password { get; set; }
public virtual bool Enabled { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string Phone { get; set; }
public virtual DateTime? DeletedDate { get; set; }
public virtual UserAccount DeletedBy { get; set; }
}
Fluent Mapping
public class UserAccountMap : ClassMap<UserAccount>
{
public UserAccountMap()
{
Table("UserAccount");
Id(x => x.Id);
Map(x => x.UserName);
Map(x => x.Password);
Map(x => x.FirstName);
Map(x => x.LastName);
Map(x => x.Phone);
Map(x => x.DeletedDate);
Map(x => x.Enabled);
}
}
Here is how I'm creating my Session Factory
var dbconfig = MySQLConfiguration
.Standard
.ShowSql()
.ConnectionString(a => a.FromAppSetting("MySqlConnStr"));
FluentConfiguration config = Fluently.Configure()
.Database(dbconfig)
.Mappings(m =>
{
var mapping = m.FluentMappings.AddFromAssemblyOf<TransactionDetail>();
mapping.ExportTo(mappingdir);
});
and this is my NHibernate code:
using (var trans = Session.BeginTransaction())
{
var user = GetById(userId);
user.Enabled = false;
user.DeletedDate = DateTime.Now;
user.UserName = "deleted_" + user.UserName;
user.Password = "--removed--";
Session.Update(user);
trans.Commit();
}
No exceptions are being thrown. No queries are being logged. Nothing.
Do you have auto flushing configured? You're calling a commit for transactions on your session but no flush on the session.