1

介绍

  • 我是实体框架的新手
  • 我正在使用代码优先

用例

我必须遵循表格

[Table("TBL_UserVariant")]
public class UserVariant
{
    [Key, Column(Order = 0)]
    public int UserId { get; set; }
    [Key, Column(Order = 1)]
    public int VarId { get; set; }
    public string Value { get; set; }
}

[Table("TBL_UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }

    public string eMail { get; set; }
}

我希望 TBL_UserProfile 引用所有 TBL_UserVariant 条目的列表,其中 TBL_UserProfile::UserId == TBL_UserVariant::UserId

以下是我的目标示例

[Table("TBL_UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }

    public string eMail { get; set; }

    public UserVariant[] variants;
}

其中 'UserProfile::variants' 应包含 'TBL_UserProfile::UserId == TBL_UserVariant::UserId' 的项目列表

问题

这可以直接使用 EF 吗?或者,我应该实现一个填充 'UserProfile::variants' ~manually~ 的包装器吗?

4

3 回答 3

0

您只需将导航属性添加到 UserProfile 实体。

    [Table("TBL_UserProfile")]
    public class UserProfile
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }

        public string eMail { get; set; }
        public virtual ICollection<UserVariant> UserVariants { get; set; }
    }
于 2013-04-09T12:58:14.807 回答
0

以下是您应该需要的。EF 将负责其余的工作。

[Table("TBL_UserProfile")]
public class UserProfile
{
    [Key]
    public int UserId { get; set; }
    public string eMail { get; set; }

    public virtual ICollection<UserVariant> Variants { get; set; }
}

[Table("TBL_UserVariant")]
public class UserVariant
{
    [Key]
    public int VarId { get; set; }
    public UserProfile User { get; set; }
    public string Value { get; set; }
}
于 2013-04-09T12:59:29.347 回答
0

我认为你要的是你想要一个UserProfile,映射到 ManyUserVariants

在这种情况下,您需要将一个集合添加到您的 UserProfile 类。

public virtual ICollection<UserVariant> UserVariants { get; set; }

您还需要修复[Key]UserVariant 类上的属性,因为我认为它应该在 VarId 上。然后,您可以只指定一个导航属性

[Key]
public int VarId { get; set; }
public UserProfile User { get; set; }

编辑

顺便说一句,您的命名约定无处不在。不要在表名前加上TBL_. 将所有属性/列大写。例如Email不是eMail

于 2013-04-09T12:59:58.783 回答