Skip to main content
 首页 » 编程设计

c#之代码优先 EF : While searching database table is it possible to retrieve list of items it has in DataModel

2024年02月13日17lexus

我有这个模型

public class Appointment 
{ 
 
    [Key] 
    public Guid Id { get; set; } 
 
    public IEnumerable<Attendee> Attendees { get; set; } 
 
    public DateTime StartDateTime { get; set; } 
    public DateTime EndDateTime { get; set; }       
} 

和 Attendee 类

public class Attendee 
{ 
    public Guid AttendeeId { get; set; } 
 
    public Guid AppointmentId { get; set; } 
    public Appointment Appointment { get; set; } 
 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string Email { get; set; } 
 
    public Boolean IsApproved { get; set; } 
    public IEnumerable<Response> Responses { get; set; }  
} 

和 DbContext 类

public class DatePickerDbContext : IdentityDbContext 
{ 
    public DatePickerDbContext():base("DefaultConnection") 
    { 
    } 
    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
        base.OnModelCreating(modelBuilder); 
        modelBuilder.Entity<IdentityUser>().ToTable("Users"); 
        modelBuilder.Entity<ApplicationUser>().ToTable("Users"); 
        modelBuilder.Entity<IdentityRole>().ToTable("Roles"); 
    } 
 
    public DbSet<Appointment> Appointments { get; set; } 
 
    public DbSet<Attendee> Attendees { get; set; } 
} 

现在当我在 Appointments 表上查询时,例如

_db.Appointments.Find(appointmentId); 

它不应该延迟加载所有与会者吗?

还是我的模型中遗漏了什么?

附言:

Entity Framework 版本:6.0.2

Asp.Net MVC 版本:5.1.0

请您参考如下方法:

要延迟加载相关类,模型中的属性应该是virtual,并且应该是ICollection,而不是IEnumerable:

public virtual ICollection<Attendee> Attendees { get; set; }