实体框架代码优先 - 定义与MembershipUser的关系

Kam*_*yar 6 entity-framework lazy-loading .net-4.0 foreign-key-relationship entity-framework-4.1

我试图理解定义我的POCO类的最佳方法,以便能够使用Entity Framework代码优先功能.
我想在我的类中定义一些外键关系,在用户之间以及类本身之间.例如,考虑以下3个类:

Public class Job
{
    public int JobID {get; set;}
    public string JobTitle {get; set;}
    public virtual ICollection<Resume> Resumes {get; set;} // Is this correct at all? How to access all resumes for a certain job? (many-to-many relationship between Job and Employee)
}

Public class Resume
{
    public int EmployeeID {get; set;} // or should it be: public virtual Employee EmployeePerson?
    public int JobID {get; set;} // or should it be: public virtual Job UserJob?
    public DateTime EmploymentDate {get; set;}
}  

public class Employee
{
    public int EmployeeID {get; set;}
    public int UserID{ger; set;} // or should it be: public virtual MembershipUser User?
    public ICollection<Resume> Resumes {get; set;} // Is this correct at all? 
}
Run Code Online (Sandbox Code Playgroud)

用户是Membership用户,System.Web.Security其中FormsAuthentication或ActiveDirectoryAuthentication正在对其进行身份验证.问题在代码中提到(作为注释).但澄清一下:

  • 我应该在关系中定义对象并在.Include每次需要时使用它们,还是更好地存储对象的ID并尝试每次需要时从该ID获取数据?在处理MembershipUser类而不是我定义的类时,我应该使用不同的方法吗?
  • virtual除了启用延迟加载之外还有什么其他用途?我应该在哪里避免它,我应该在哪里使用它?

谢谢.

更新:我刚刚测试了定义Employee的ublic virtual MembershipUser User定义.结果是我的表中添加了4个列:

  • USER_EMAIL,
  • USER_COMMENT,
  • User_IsApproved,
  • User_LastLoginDate,
  • User_LastActivityDate

用户没有任何独特之处(User_Email被定义为可空).因此,如果您希望在您的类中拥有用户,请为其创建包装器MembershipUser或仅存储UserID.
谢谢Ladislav和Sergi.

Ser*_*eit 5

我建议将外键声明为导航属性,这样您就可以直接访问相关属性,而无需自己从数据库中显式检索它(它将被延迟加载).

所以你的模型看起来像:

public class Resume
{
    public int ID {get; set;}
    // or should it be: public virtual Employee EmployeePerson? 
    // --> yep, easier for you, innit?
    public Employee Employee {get; set;} 

    // or should it be: public virtual Job UserJob? --> yep :)
    public virtual Job Job {get; set;}

    public DateTime EmploymentDate {get; set;}
}  

public class Employee
{
    public int EmployeeID {get; set;}

    // or should it be: public virtual MembershipUser User? 
    // --> yes, as an approach, but read on for clarification.
    public virtual MembershipUser User {get; set;}

    // Is this correct at all? ---> needs to be declared as virtual
    public virtual ICollection<Resume> Resumes {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

Job据我所知,你的班级还可以.

要清楚,它最初会像使用它一样使用它,但你需要明确标记属性,ForeignKeyAttribute如果你愿意放弃对方式的一点点控制,这是不必要的. FK在您的数据库中命名.