Lazy, Eager and Explicit loading is not working in Entity Framework 5 - entity-framework

Department class:
public partial class Department
{
public Department()
{
this.Courses = new HashSet<Course>();
}
public int DepartmentID { get; set; }
public string Name { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
Course class:
public partial class Course
{
public Course()
{
this.Enrollments = new HashSet<Enrollment>();
this.People = new HashSet<Person>();
}
public int CourseID { get; set; }
public string Title { get; set; }
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
}
Context:
lazy loading is enabled as below.
universityDBContext.Configuration.LazyLoadingEnabled = true;
universityDBContext.Configuration.ProxyCreationEnabled = true;
Lazy loading is not working in Entity Framework 5. Please help

public partial class Department
{
public Department()
{
this.Courses = new HashSet<Course>();
this.Students = new HashSet<Student>();
}
public int DepartmentID { get; set; }
public string Name { get; set; }
public decimal Budget { get; set; }
public System.DateTime StartDate { get; set; }
public Nullable<int> InstructorID { get; set; }
public byte[] RowVersion { get; set; }
public virtual ICollection<Course> Courses { get; set; }
public virtual ICollection<Student> Students { get; set; }
public virtual Person Person { get; set; }
}

public partial class Course
{
public Course()
{
this.Enrollments = new HashSet<Enrollment>();
this.People = new HashSet<Person>();
}
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public int DepartmentID { get; set; }
public byte[] rowversion { get; set; }
[ForeignKey("Department")]
public virtual Department Department { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
public virtual ICollection<Person> People { get; set; }
}

Related

Insert/Add new entity with nested children entities to DB using Entity Framework Core

Here are Entities:
public class Entity
{
public int Id { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? ModifiedOn { get; set; }
}
public class EntityBase : Entity
{
[ForeignKey("CreatedBy")]
public int CreatedById { get; set; }
public User CreatedBy { get; set; }
[ForeignKey("ModifiedBy")]
public int? ModifiedById { get; set; }
public User ModifiedBy { get; set; }
}
public class ProjectRequest : EntityBase
{
public string RequestTitle { get; set; }
public string RequestType { get; set; }
...
public virtual ICollection<Material> Materials { get; set; }
public virtual ICollection<Translation> Translations { get; set; }
}
public class Material : EntityBase
{
[ForeignKey("ProjectRequest")]
public int ProjectRequestId { get; set; }
public virtual ProjectRequest ProjectRequest { get; set; }
...
public virtual ICollection<Translation> Translations { get; set; }
}
public class Translation:EntityBase
{
[ForeignKey("ProjectRequest")]
public int ProjectRequestId { get; set; }
public virtual ProjectRequest ProjectRequest { get; set; }
[ForeignKey("Material")]
public int MaterialId { get; set; }
public virtual Material Material { get; set; }
public string ProductMasterText { get; set; }
[MaxLength(40)]
public string ShortDescription { get; set; }
public string MasterDescriptionLine1 { get; set; }
public string MasterDescriptionLine2 { get; set; }
public string MasterDescriptionLine3 { get; set; }
public string LanguageCode { get; set; }
}
No modifications has been done to these entities using fluent API.
Now, whenever I try to insert object of type ProjectRequest with Materials and Translations nested in it, in Translation objects ProjectRequestId is set to 0.
Following is sample Change Tracker snapshot:
Can anyone help me on this? Why ProjectRequestId is 0 but MaterialId properly assigned in Transaltion objects?

Including multiple child layers in LINQ to SQL

I have a data model which has three layers as follows:
Market Message
MessageType598
Metered Generation Information
The classes are as follows:
[Table("MarketMessage")]
public partial class MarketMessage
{
public MarketMessage()
{
messageType300 = new HashSet<messageType300>();
messageType300S = new HashSet<messageType300S>();
messageType300W = new HashSet<messageType300W>();
messageType305 = new HashSet<messageType305>();
messageType310 = new HashSet<messageType310>();
messageType310W = new HashSet<messageType310W>();
messageType320 = new HashSet<messageType320>();
messageType320W = new HashSet<messageType320W>();
messageType332 = new HashSet<messageType332>();
messageType332W = new HashSet<messageType332W>();
messageType591 = new HashSet<messageType591>();
messageType594 = new HashSet<messageType594>();
messageType595 = new HashSet<messageType595>();
messageType596 = new HashSet<messageType596>();
messageType597 = new HashSet<messageType597>();
messageType598 = new HashSet<messageType598>();
}
public int MarketMessageID { get; set; }
public DateTime CreatedOn { get; set; }
[Required]
[StringLength(4)]
public string messageType { get; set; }
[Required]
[StringLength(8)]
public string VersionNumber { get; set; }
public DateTime MarketTimestamp { get; set; }
[Required]
[StringLength(35)]
public string TxRefNbr { get; set; }
[Required]
[StringLength(3)]
public string Sender { get; set; }
[Required]
[StringLength(3)]
public string Recipient { get; set; }
[StringLength(10)]
public string alertFlag { get; set; }
[StringLength(50)]
public string fileName { get; set; }
public bool IsDeleted { get; set; }
public virtual ICollection<messageType300> messageType300 { get; set; }
public virtual ICollection<messageType300S> messageType300S { get; set; }
public virtual ICollection<messageType300W> messageType300W { get; set; }
public virtual ICollection<messageType305> messageType305 { get; set; }
public virtual ICollection<messageType310> messageType310 { get; set; }
public virtual ICollection<messageType310W> messageType310W { get; set; }
public virtual ICollection<messageType320> messageType320 { get; set; }
public virtual ICollection<messageType320W> messageType320W { get; set; }
public virtual ICollection<messageType332> messageType332 { get; set; }
public virtual ICollection<messageType332W> messageType332W { get; set; }
public virtual ICollection<messageType591> messageType591 { get; set; }
public virtual ICollection<messageType594> messageType594 { get; set; }
public virtual ICollection<messageType595> messageType595 { get; set; }
public virtual ICollection<messageType596> messageType596 { get; set; }
public virtual ICollection<messageType597> messageType597 { get; set; }
public virtual ICollection<messageType598> messageType598 { get; set; }
}
public partial class messageType598
{
public int messageType598ID { get; set; }
public int MarketMessageID { get; set; }
public DateTime SettlementDate { get; set; }
public int SettlementRunIndicator { get; set; }
[Required]
[StringLength(9)]
public string GenerationUnit { get; set; }
}
[Table("MeteredGenerationInformation")]
public partial class MeteredGenerationInformation
{
[Key]
public int MeteredGenerationInfoID { get; set; }
public DateTime IntervalPeriodTimestamp { get; set; }
public int SettlementInterval { get; set; }
public decimal GenerationUnitMeteredGeneration { get; set; }
public decimal LossAdjustedGenerationUnitMeteredGeneration { get; set; }
public int? MessageType594ID { get; set; }
public int? MessageType598ID { get; set; }
}
I am attempting to join a list of all market messages received of type 598 including the metered generation information but I am unsure how to do this via LINQ to SQL. I have attempted the following:
var list598s = db.MarketMessage.Where(mm => mm.messageType == "598")
.Include(mm => mm.messageType598)
.ToList();
This includes the market messages including the 598 information but how can I include the metered generation information also in this list, I would also ideally like to refine the list based on a date field found within the messageType598 level
As a SQL query I would write the following:
select * from MarketMessage as a
inner join messageType598 as b on a.MarketMessageID = b.MarketMessageID
inner join MeteredGenerationInformation as c on b.messageType598ID = c.messageType598ID
where c.IntervalPeriodTimestamp between '1 aug 2016' and '31 aug 2016'

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;
}

Entity Framework [Key] tag not being recognised

I am getting warning errors of no key having been defined for each of my class library classes despite the fact that I have the [Key] tag and including the System.ComponentModel.DataAnnotations namespace, here is my context:
Context:
namespace Project.Data
{
public class ProjectContext : DbContext, IProjectContext
{
public ProjectContext(string connString)
: base(connString)
{
this.Configuration.LazyLoadingEnabled = true;
Database.SetInitializer<ProjectContext>(new ProjectInitializer());
this.Database.CreateIfNotExists();
this.Database.Initialize(true);
}
public IDbSet<Article> Article { get; set; }
public IDbSet<Brand> Brand { get; set; }
public IDbSet<Colour> Colour { get; set; }
public IDbSet<Customer> Customer { get; set; }
public IDbSet<CustomerCredit> CustomerCredit { get; set; }
public IDbSet<Delivery> Delivery { get; set; }
public IDbSet<DesignerTicket> DesignerTicket { get; set; }
public IDbSet<EuroRate> EuroRate { get; set; }
public IDbSet<Gift> Gift { get; set; }
public IDbSet<GZero> GZero { get; set; }
public IDbSet<InvoiceStock> InvoiceStock { get; set; }
public IDbSet<PrintOptions> PrintOptions { get; set; }
public IDbSet<Product> Product { get; set; }
public IDbSet<ProductLocation> ProductLocation { get; set; }
public IDbSet<Sale> Sale { get; set; }
public IDbSet<SaleAccount> SaleAccount { get; set; }
public IDbSet<SalesToWeb> SalesToWeb { get; set; }
public IDbSet<Shop> Shop { get; set; }
public IDbSet<Staff> Staff { get; set; }
public IDbSet<Ticket> Ticket { get; set; }
public IDbSet<Transfer> Transfer { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
Context Interface:
namespace Project.Data
{
public interface IProjectContext
{
IDbSet<Article> Article { get; set; }
IDbSet<Brand> Brand { get; set; }
IDbSet<Colour> Colour { get; set; }
IDbSet<Customer> Customer { get; set; }
IDbSet<CustomerCredit> CustomerCredit { get; set; }
IDbSet<Delivery> Delivery { get; set; }
IDbSet<DesignerTicket> DesignerTicket { get; set; }
IDbSet<EuroRate> EuroRate { get; set; }
IDbSet<Gift> Gift { get; set; }
IDbSet<GZero> GZero { get; set; }
IDbSet<InvoiceStock> InvoiceStock { get; set; }
IDbSet<PrintOptions> PrintOptions { get; set; }
IDbSet<Product> Product { get; set; }
IDbSet<ProductLocation> ProductLocation { get; set; }
IDbSet<Sale> Sale { get; set; }
IDbSet<SaleAccount> SaleAccount { get; set; }
IDbSet<SalesToWeb> SalesToWeb { get; set; }
IDbSet<Shop> Shop { get; set; }
IDbSet<Staff> Staff { get; set; }
IDbSet<Ticket> Ticket { get; set; }
IDbSet<Transfer> Transfer { get; set; }
}
}
[Key] decorated class example:
namespace Project.Data
{
public class Article
{
[Key]
public int ArticleID;
public bool IsCore;
public string Make;
public string Product;
public decimal Sale;
public string Department;
public string Scale;
public string Detail;
public DateTime InDate;
public decimal Reduce;
public bool IsOnSale;
public string VAT;
public bool IsOnWeb;
public string ProductCode;
public string Pick;
public string MemoDetail;
public string LOC;
public string ColourCode;
public bool StatusFlag;
public string Terminal;
}
}
Despite have the [Key] placed on Article I am getting the following message for the article class as shown below and this is repeated for each of the classes:
Project.Data.Article: : EntityType 'Article' has no key defined. Define the key for this EntityType.
Anyone see what I am doing wrong here? would be greatly appreciated
Define the members of your class as public properties as opposed to public variables like you have here, by including {get; set;} at the end of the declaration

Code first fluent api - table relationship

I have following tables and need to set relationship between them.
Model classes for the tables are as given
public class UserAction
{
public int ActionID { get; set; }
public string ActionName { get; set; }
public virtual ICollection<RoleScreenActionPermission> RoleScreenActionPermissions { get; set; }
}
public class Screen
{
public int ScreenID { get; set; }
public string ScreenName { get; set; }
public virtual ICollection<RoleScreenActionPermission> RoleScreenActionPermissions { get; set; }
}
public class ScreenAction
{
public int ScreenActionID { get; set; }
public int ScreenID { get; set; }
public int ActionID { get; set; }
public virtual Screen Screen { get; set; }
public virtual UserAction UserAction { get; set; }
}
public class RoleScreenActionPermission
{
public int RoleScreenActionPermissionID { get; set; }
public int ScreenActionID { get; set; }
public int RoleID { get; set; }
public virtual ScreenAction ScreenAction { get; set; }
public virtual Role Role { get; set; }
}
The talbe structure created is as:
Please help with setting the relationship correctly.
Try to remove all your own foreign keys from your classes. EF must make it.
upd:
public class Screen
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Action
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ScreenAction
{
public int Id { get; set; }
public virtual Screen Screen { get; set; }
public virtual Action Action { get; set; }
}
public class RoleScreenActionPermission
{
public int Id { get; set; }
public virtual ScreenAction ScreenAction { get; set; }
public virtual Role Role { get; set; }
}