EF Not Lazy Loading ApplicationUser - c#

I am trying to figure out why EF is lazy loading everything but my ApplicationUser property. I am using a generic repository pattern with the following domain object.
public class Order
{
[Key]
public Guid Id { get; set; }
public int PaymentTransactionId { get; set; }
public string CustomerId { get; set; }
public int ChildId { get; set; }
public DateTime PickUpDate { get; set; }
public PickUpTime PickUpTime { get; set; }
public string Notes { get; set; }
public decimal Discount { get; set; }
public decimal SubTotal { get; set; }
public decimal Tax { get; set; }
public decimal Total { get; set; }
public DateTime DateCreated { get; set; }
public string CreatedBy { get; set; }
public OrderStatus Status { get; set; }
public virtual ApplicationUser Customer { get; set; }
public virtual Child Child { get; set; }
public virtual PaymentTransaction PaymentTransaction { get; set; }
public virtual PromotionCode PromotionCode { get; set; }
}
I've tried doing the following
context.Configuration.LazyLoadingEnabled = true;
All the virtual properties except ApplicationUser get populated when I retrieve the entity from the database.
DBCONTEXT
public class DatabaseContext : IdentityDbContext<ApplicationUser>
{
public DatabaseContext()
: base("name=DefaultContext")
{
Database.SetInitializer<DatabaseContext>(null);
Configuration.LazyLoadingEnabled = true;
}
public IDbSet<PromotionCode> Promotions { get; set; }
public IDbSet<PaymentTransaction> PaymentTransactions { get; set; }
public IDbSet<BakeryOrder> BakeryOrders { get; set; }
public IDbSet<Child> Children { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BakeryOrder>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>()
.ToTable("Users");
modelBuilder.Entity<ApplicationUser>()
.ToTable("Users");
}
public static DatabaseContext Create()
{
return new DatabaseContext();
}
}
REPOSITORY
public class Repository<T> : IRepository<T> where T : class
{
protected DatabaseContext Context;
public Repository(DatabaseContext context)
{
Context = context;
}
public IEnumerable<T> Get()
{
return Context.Set<T>();
}
}
SERVICE
public IEnumerable<Order> Get()
{
return _orderRepository.Get();
}
Am I missing something here? This did work for some time and suddenly stopped, I have no idea why... the code base hasn't changed according to the commit logs.

Entity framework doesn't know what key to map it to because you don't have any property named "ApplicationUserId" so you must explicitly add the attribute pointing to the right foreign key.
public class Order
{
[Key]
public Guid Id { get; set; }
public int PaymentTransactionId { get; set; }
public string CustomerId { get; set; }
public int ChildId { get; set; }
public DateTime PickUpDate { get; set; }
public PickUpTime PickUpTime { get; set; }
public string Notes { get; set; }
public decimal Discount { get; set; }
public decimal SubTotal { get; set; }
public decimal Tax { get; set; }
public decimal Total { get; set; }
public DateTime DateCreated { get; set; }
public string CreatedBy { get; set; }
public OrderStatus Status { get; set; }
[ForeignKey("CustomerId")]
public virtual ApplicationUser Customer { get; set; }
public virtual Child Child { get; set; }
public virtual PaymentTransaction PaymentTransaction { get; set; }
public virtual PromotionCode PromotionCode { get; set; }
}

Related

Entity Framework Relationships two tables

I'm trying to create a Friendship mapping table that has 2 FK's that originate from the same class (User and SportsFacility)
Here are my model classes.
public partial class User
{
[Key]
public int Id { get; set; }
[Required]
public int AcountId { get; set; }
[Required]
[MaxLength(20)]
//[Column(TypeName = "varchar")]
public string Login { get; set; }
[Required]
[MaxLength(20)]
public string Name { get; set; }
[Required]
public string Password { get; set; }
public virtual ICollection<CheckQueue> ChecksQueue { get; set; }
public virtual ICollection<BookedEvent> BookedEvents { get; set; }
}
public partial class SportsFacility
{
public SportsFacility()
{
ChecksQueue = new List<CheckQueue>();
BookedEvent = new List<BookedEvent>();
}
[Key]
public int Id { get; set; }
[Required]
[MaxLength(30)]
public string Name { get; set; }
[Required]
public int PnH_Id { get; set; }
[Required]
[MaxLength(70)]
public string Address { get; set; }
public int City_Id { get; set; }
[ForeignKey("City_Id")]
public virtual City City { get; set; }
public virtual ICollection<CheckQueue> ChecksQueue { get; set; }
public virtual ICollection<BookedEvent> BookedEvent { get; set; }
}
public partial class CheckQueue
{
[Key]
public int Id { get; set; }
public DateTime StartCheckTime { get; set; }
[Required]
public string CheckParams { get; set; }
public string Error { get; set; }
public bool IsDeleted { get; set; }
public int User_Id { get; set; }
[ForeignKey("User_Id")]
public virtual User User { get; set; }
public int SportsFacility_Id { get; set; }
[ForeignKey("SportsFacility_Id")]
public virtual SportsFacility SportsFacility { get; set; }
[Index]
public DateTime? LastCheck { get; set; }
}
public partial class BookedEvent
{
[Key]
public int Id { get; set; }
public DateTime BookDate { get; set; }
[Required]
public string CheckParams { get; set; }
public string Error { get; set; }
public bool IsDeleted { get; set; }
public int User_Id { get; set; }
[ForeignKey("User_Id")]
public virtual User User { get; set; }
public int SportsFacility_Id { get; set; }
[ForeignKey("SportsFacility_Id")]
public virtual SportsFacility SportsFacility { get; set; }
}
I tried override the OnModelCreating method in the DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<City>();
modelBuilder.Entity<SportsFacility>();
modelBuilder.Entity<User>();
modelBuilder.Entity<CheckQueue>();
modelBuilder.Entity<BookedEvent>();
base.OnModelCreating(modelBuilder);
}
This causes a new error message to be displayed.
Additional information: The entity types 'BookedEvent' and 'CheckQueue' cannot share table 'CheckQueues' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them.
Any help would be greatly appreciated.

Code-first Entity Framework may to many relation with additional fields not working

I have 3 classes that must be in a many-to-many relationship, but when I run my project, Entity Framework can't map them to SQL Server tables. I used migrations.
My user class is here:
[Table("tbl_User")]
public class User
{
public User()
{
}
#region Properties
[Key]
[Required][DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string LoginName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public bool EmailVerify { get; set; }
public string Image { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
public DateTime LoginDate { get; set; }
public bool Enabled { get; set; }
public bool Deleted { get; set; }
#endregion
#region Relations
public virtual IList<UserRole> UserRole { get; set; }
#endregion Relations
}
Role class is here:
[Table("tbl_Role")]
public class Role
{
public Role()
{
}
#region Properties
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string RoleName { get; set; }
public int Order { get; set; }
public string Icon { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
public bool Enable { get; set; }
public bool Deleted { get; set; }
#endregion Properties
#region Relations
public virtual IList<UserRole> UserRole { get;set;}
#endregion Relations
}
UserRole is my many-to-many relationship table:
[Table("tbl_UserRole")]
public class UserRole
{
internal class Configuration : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<UserRole>
{
public Configuration()
{
HasRequired(current => current.User)
.WithMany(userrole => userrole.UserRole)
.HasForeignKey(fk => fk.UserId);
HasRequired(current => current.Role)
.WithMany(userrole => userrole.UserRole)
.HasForeignKey(fk => fk.RoleId);
}
}
public UserRole()
{
}
#region Properties
[Key]
[Required]
public long Id { get; set; }
public DateTime GrantDate { get; set; }
public DateTime ExpireDate { get; set; }
public bool Enabled { get; set; }
public bool Deleted { get; set; }
#endregion Properties
#region Relations
public long UserId { get; set; }
public virtual User User { get; set; }
public int RoleId { get; set; }
public virtual Role Role { get; set; }
#endregion Relations
}
and here is my database context
public class LiveMiracleDbContext:DbContext
{
public LiveMiracleDbContext() : base("LMConnection")
{
}
public DbSet<User> tbl_User { get; set; }
public DbSet<Role> tbl_Role { get; set; }
public DbSet<UserRole> tbl_UserRole { get; set; }
}
When I run my project without these classes, my database is generated, but when I use these classes, my database is not generated.
ok tanks for Gert Arnold comment
problem was in my Attributes this stracture is true
i removed attributes.

Entity Framework (EF) code first migration creates only some of the tables

I am running my initial EF migration trying to create the database.
But only 3 of my 5 domains are being created as tables in the database. No errors occur during migration.
I try to run SeedData methods on run, but of course it stops when it tries to save data to the table that does not exist.
I am using EF7. I use DNX to run migrations.
Does anyone know why only 3 of the tables are being created?
Here are the 2 tables that did NOT get created:
// Enumclass, this is not a table
public enum MatchTypeEnum
{
Group, RoundOf32, RoundOf16, QuarterFinals, SemiFinals, BronzeFinal, Final
}
public partial class Match
{
[Key]
public Guid MatchId { get; set; }
public DateTime KickOffTime { get; set; }
public int? HomeScore { get; set; }
public int? AwayScore { get; set; }
public Guid HomeTeamId { get; set; }
public Guid AwayTeamId { get; set; }
public MatchTypeEnum MatchType { get; set; }
public Guid? GroupId { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team AwayTeam { get; set; }
[ForeignKey("GroupId")]
public virtual Group Group { get; set; }
}
public enum MatchOutcomeEnum
{
H,A,D
}
public partial class Bet
{
[Key]
public Guid BetId { get; set; }
public Guid UserId { get; set; }
public Guid MatchId { get; set; }
public int? HomeScore { get; set; }
public int? AwayScore { get; set; }
public MatchOutcomeEnum? MatchOutcome{ get; set; }
public int? PointsCorrectScore { get; set; }
public int? PointsBonus { get; set; }
public int? MultiplyScoreWith { get; set; }
public int? TotalPointsBet { get; set; }
[ForeignKey("MatchId")]
public virtual Match MatchBettedOn { get; set; }
}
And here are the 3 classes that do get created:
public class Team
{
[Key]
public Guid TeamId { get; set; }
public string TeamName { get; set; }
public string TeamCountry { get; set; }
public Guid GroupId { get; set; }
public string LogoUrl { get; set; }
[ForeignKey("GroupId")]
public virtual Group TeamGroup { get; set; }
}
public enum GroupEnum
{
GroupA, GroupB, GrooupC, GroupD,GroupE,GroupF, GroupG, GroupH, GroupI
}
/// <summary>
/// The group.
/// </summary>
public partial class Group
{
[Key]
public Guid GroupId { get; set; }
public GroupEnum GroupName { get; set; }
public int? NumberTeamsProceed { get; set; }
public virtual ICollection<Team> TeamsInGroup { get; set; }
public virtual ICollection<Match> MatchesInGroup { get; set; }
}
public class League
{
[Key]
public Guid LeagueId { get; set; }
public string LeagueName { get; set; }
public bool Public { get; set; }
public int LeagueNumber { get; set; }
public string LeagueLink { get; set; }
}
The DbContext:
public class CupBettingContext : DbContext
{
public CupBettingContext()
{
Database.EnsureCreated();
}
public DbSet<Group> Groups { get; set; }
public DbSet<Match> Matches { get; set; }
public DbSet<Bet> Bets { get; set; }
public DbSet<League> Leagues { get; set; }
public DbSet<Team> Teams { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connectionString = Startup.Configuration["Data:CupBettingContextConnection"];
optionsBuilder.UseSqlServer(connectionString);
base.OnConfiguring(optionsBuilder);
}
}
Thank you for your time :)
UPDATE:
It worked after I I removed the two lines from the class Match:
public virtual Team HomeTeam { get; set; }
public virtual Team AwayTeam { get; set; }
Strange that it ran the migration :/
If anyone is still reading this question, how can I add those virtual object without getting an error?

How map two properties to the same table using mvc 5 and EntityFramework code first?

I have this class....
public class ApplicationUser : IdentityUser
{
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public virtual ICollection<Post> PostsCreated { get; set; }
public virtual ICollection<Post> PostsModified { get; set; }
public virtual Comment Comment { get; set; }
}
And the other class is this...
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public virtual ICollection<Category> Category { get; set; }
public DateTime PublishDate { get; set; }
public DateTime CreateDate { get; set; }
//----------------------------------------------------------------
[ForeignKey("UserCreated"), Column(Order = 0)]
public string CreatedId { get; set; }
[ForeignKey("UserModify"), Column(Order = 1)]
public string ModifiedId { get; set; }
//----------------------------------------------------------------
[InverseProperty("PostsCreated")]
public virtual ICollection<ApplicationUser> UserCreated { get; set; }
[InverseProperty("PostsModified")]
public virtual ICollection<ApplicationUser> UserModify { get; set; }
//----------------------------------------------------------------
public DateTime ModifiedDate { get; set; }
public Public Public { get; set; }
}
My data acces is this.....
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("BlogLibrary2")
{
}
public DbSet<Post> Post { get; set; }
public DbSet<Comment> Comment { get; set; }
public DbSet<Category> Category { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
}
And I got this error when I try to create a controller using this data acces and the Post class:
There was an error running the selected code generator: 'Unable to retrieve metadata for 'LibraryBlog.Models.Post'. The foreign key component 'CreatedId' is not a declared property on type 'ApplicationUser'.Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.'
I fixed that error. I modified this class and now look like this:
public class ApplicationUser : IdentityUser
{
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public virtual ICollection<Post> PostsCreated { get; set; }
public virtual ICollection<Post> PostsModified { get; set; }
public virtual Comment Comment { get; set; }
}
And this one:
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public virtual ICollection<Category> Category { get; set; }
public DateTime PublishDate { get; set; }
public DateTime CreateDate { get; set; }
//---------------------Here is the point
public string PostCreatedBy { get; set; }
public string PostModifiedBy { get; set; }
[ForeignKey("PostCreatedBy"), InverseProperty("PostsCreated")]
public virtual ApplicationUser CreatedBy { get; set; }
[ForeignKey("PostModifiedBy"), InverseProperty("PostsModified")]
public virtual ApplicationUser ModifiedBy { get; set; }
//-------------------------------------------
public DateTime ModifiedDate { get; set; }
public Public Public { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("BlogLibrary2")
{
}
public DbSet<Post> posts { get; set; }
public DbSet<Comment> comments { get; set; }
public DbSet<Category> categories { get; set; }
}
Would you please edit the code with the above one. Hope this helps..

How to Map many one-to-many relationship in ASP.NET MVC?

I have few Domain Models - Address, Customer, Employee, StoreLocation. Address has many to one relationship with Customerand Employee and one to one relationship with StoreLocation.
public class Address
{
public int Id;
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Address> Addresses { get; set; }
}
public class StoreLocation
{
public int Id { get; set; }
public string ShortCode { get; set; }
public string Description { get; set; }
public Address Address { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Dob { get; set; }
public IList<Address> Addresses { get; set; }
}
How to Map this relationship?. I am using ASP.NET MVC 3.0 and Entity Framework 4.1.
If you are using code-first (I think you want this, else, you have to edit your Q), the first way is the way explained below:
Entities:
public class Address {
[Key]
public int Id { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public virtual Customer Customer { get; set; }
public virtual StoreLocation StoreLocation { get; set; }
public virtual Employee Employee { get; set; }
public int? CustomerId { get; set; }
public int? EmployeeId { get; set; }
}
public class Customer {
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
public class StoreLocation {
[Key]
public int Id { get; set; }
public string ShortCode { get; set; }
public string Description { get; set; }
public virtual Address Address { get; set; }
}
public class Employee {
[Key]
public int Id { get; set; }
public string Name { get; set; }
public DateTime Dob { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
DbContext inherited class:
public class ManyOneToManyContext : DbContext {
static ManyOneToManyContext() {
Database.SetInitializer<ManyOneToManyContext>(new ManyOneToManyInitializer());
}
public DbSet<Address> Addresses { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<StoreLocation> StoreLocations { get; set; }
public DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
modelBuilder.Entity<Customer>().HasMany(c => c.Addresses).WithOptional(a => a.Customer).HasForeignKey(a => a.CustomerId);
modelBuilder.Entity<StoreLocation>().HasRequired(s => s.Address).WithOptional(a => a.StoreLocation).Map(t => t.MapKey("AddressId"));
modelBuilder.Entity<Employee>().HasMany(e => e.Addresses).WithOptional(a => a.Employee).HasForeignKey(e => e.EmployeeId);
}
}
Context Initializer:
public class ManyOneToManyInitializer : DropCreateDatabaseAlways<ManyOneToManyContext> {
protected override void Seed(ManyOneToManyContext context) {
}
}
That will create the db-schema below:
Let me know if you have any questions or need clarifications on any part.

Categories

Resources