如何使用 fluent api 命名地图关联

Posted

技术标签:

【中文标题】如何使用 fluent api 命名地图关联【英文标题】:How to name a map association with fluent api 【发布时间】:2013-11-20 18:52:40 【问题描述】:

到目前为止,我已经在数据库表之间建立了一个流畅的 api 关联。

示例:

//Map Skill Associations
modelBuilder.Entity<Skill>()
    .HasMany( s => s.Employees ).WithMany( e => e.Skills )
    .Map( m => 
        m.ToTable( "Employee_Skill" );
        m.MapLeftKey( "SkillID" );
        m.MapRightKey( "EmployeeID" );
     );

//Map Employee Associations
modelBuilder.Entity<Employee>()
    .HasMany( e => e.Skills ).WithMany( s => s.Employees )
    .Map( m => 
        m.ToTable( "Employee_Skill" );
        m.MapLeftKey( "EmployeeID" );
        m.MapRightKey( "SkillID" );
     );

//Map Client Properties to Fields
modelBuilder.Entity<Employee>()
    .HasKey( e => e.EmployeeId).ToTable( "Employee" );
modelBuilder.Entity<Employee>()
    .Property( e => e.EmployeeId ).HasColumnName( "id" );
modelBuilder.Entity<Employee>()
    .Property( e => e.FirstName ).HasColumnName( "fname" );
modelBuilder.Entity<Employee>()
    .Property( e => e.LastName ).HasColumnName( "lname" );
modelBuilder.Entity<Employee>()
    .Property( e => e.LinkedIn ).HasColumnName( "linkedin" );
modelBuilder.Entity<Employee>()
    .Property( e => e.Active ).HasColumnName( "active" );
modelBuilder.Entity<Employee>()
    .Property( e => e.Inactive ).HasColumnName( "inactive" );
modelBuilder.Entity<Employee>()
    .Property( e => e.Created ).HasColumnName( "created" );

//Map Skill Properties to Fields
modelBuilder.Entity<Skill>()
    .HasKey(s => s.SkillId).ToTable( "Skill" );
modelBuilder.Entity<Skill>()
    .Property( s => s.SkillId ).HasColumnName( "id" );
modelBuilder.Entity<Skill>()
    .Property( s => s.Name ).HasColumnName( "name" );
modelBuilder.Entity<Skill>()
    .Property( s => s.Description ).HasColumnName( "description" );
modelBuilder.Entity<Skill>()
    .Property( s => s.Active ).HasColumnName( "active" );
modelBuilder.Entity<Skill>()
    .Property( s => s.Inactive ).HasColumnName( "inactive" );

过去我处理过 DBMX 文件并完成实体之间的视觉关联。在代码中,当我想加载关联时,我会执行 Context.Employees.Include("Skills") 之类的操作,以确保 Employee 实体将关联的技能加载到返回集合中。

使用 Fluent,我如何在需要时使用相同的语法结构来加载(认为它称为 LazyLoading)Collection 对象,否则不会自动加载它们。

我似乎没有任何选项可以让我将技能或员工关联命名为相应的实体。

任何帮助将不胜感激。

【问题讨论】:

【参考方案1】:

要使用 LazyLoading,您应该在模型类中将属性定义为虚拟。无需更改 Fluent 配置:

class Skill

    ...
    public virtual List<Employee> Employees  get; set; 


class Employee

    ...
    public virtual List<Skill> Skills  get; set; 

阅读更多关于 LazyLoading here

【讨论】:

您说要使用 virtual,但您的代码示例缺少 virtual 关键字 @Alexander:我明白你的意思。曾经玩弄过这个想法。刷新我的记忆,虚拟方法仅在我访问数据部分时才加载数据正确吗?像Employee.Skills 之类的东西,还是我需要使用Include("Skills") 来为属性加载数据? 对不起,忘了虚拟) 我正在尝试将内存中的数据负载保持在最低限度。 @GoldBishop,确切地说。直到,您不调用 Employee.Skills,才不会加载 Skills 对象。

以上是关于如何使用 fluent api 命名地图关联的主要内容,如果未能解决你的问题,请参考以下文章