繁体   English   中英

实体框架表关系

[英]Entity Framework table relations

介绍

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

用例

我必须跟随桌子

[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”的包装器吗?

您只需将导航属性添加到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; }
    }

以下是您需要的内容。 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; }
}

我认为您要的是要拥有一个UserProfile ,映射到Many UserVariants

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

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

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

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

编辑

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM