C# 实体框架表关系 介绍 我不熟悉实体框架 我先用代码 用例
我必须遵守以下表格C# 实体框架表关系 介绍 我不熟悉实体框架 我先用代码 用例,c#,asp.net,entity-framework,C#,Asp.net,Entity Framework,我必须遵守以下表格 [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_User
[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,映射到多个UserVariants 在这种情况下,您需要向UserProfile类添加一个集合
public virtual ICollection<UserVariant> UserVariants { get; set; }
编辑
顺便说一句,你的命名惯例到处都是。不要在表名的前面加上TBL_。将所有属性/列大写。e、 g.Email not EmailEF如何知道只有'TBL_UserProfile::UserId==TBL_UserVariant::UserId'的行?当您第一次使用UserVariants属性时,EF从用户id相等的TBL_UserVariant表中查询记录。这将如何使UserVariants只包含那些“TBL_UserProfile::UserId==TBL_UserVariant::UserId”的条目?EF将处理这个问题。尝试分析它生成的SQL代码,您将看到如何进行分析。
[Key]
public int VarId { get; set; }
public UserProfile User { get; set; }