实体框架表关系
本文关键字:关系 框架 实体 | 更新日期: 2023-09-27 18:08:19
简介
- 我是实体框架的新手
- 我首先使用代码
用例
我必须遵循表格
[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::variations"应包括一个项目列表,其中"TBL_UserProfile::UserId==TBL_UserVariant::UserId">
问题
使用EF可以直接实现这一点吗?或者,我应该实现一个包装器来填充"UserProfile::variations"~手动~吗?
您只需要向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; }
您还需要修复UserVariant类上的[Key]
属性,因为我认为它应该在VarId上。然后您可以指定一个导航属性
[Key]
public int VarId { get; set; }
public UserProfile User { get; set; }
编辑
顺便说一句,你的命名约定无处不在。不要在表名前面加上TBL_
。将您的所有财产/栏资本化。例如Email
而非eMail