EF не отложенная загрузка ApplicationUser

Я пытаюсь понять, почему EF лениво загружает все, кроме моего свойства ApplicationUser. Я использую общий шаблон репозитория со следующим объектом домена.

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

Я пытался сделать следующее

context.Configuration.LazyLoadingEnabled = true;

Все виртуальные свойства, кроме ApplicationUser, заполняются, когда я извлекаю объект из базы данных.

ДБКОНТЕКСТ

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

РЕПОЗИТОРИЙ

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

ОКАЗАНИЕ УСЛУГ

public IEnumerable<Order> Get()
{
    return _orderRepository.Get();
}

Я что-то упустил здесь? Это работало какое-то время и внезапно остановилось, я понятия не имею, почему... кодовая база не изменилась в соответствии с журналами коммитов.


person devfunkd    schedule 31.10.2014    source источник


Ответы (1)


Платформа Entity не знает, с каким ключом его сопоставить, потому что у вас нет свойства с именем «ApplicationUserId», поэтому вы должны явно добавить атрибут, указывающий на правильный внешний ключ.

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; }
}
person TysonWolker    schedule 31.10.2014
comment
Я думал, что это сработало из имени свойства, CustomerId и Customer? Я попробую. - person devfunkd; 31.10.2014
comment
действительно, Customer и CustomerId достаточно, вам не нужно указывать атрибут внешнего ключа. - person badr slaoui; 04.01.2016