在 entity framework 核心中,当两个字段映射到另一个 table 的主键时,我们如何为 table 设置关系
In entity framework core, how we can set relationship for a table, when two fields is mapping to primary key of the another table
在 entity framework 核心中,当两个字段映射到另一个 table 的主键时,我们如何为 table 设置关系。
例如我有两个 table 即 Users & CashBox.
用户Table
Field
Value
UserId
int
UserName
string
钱箱Table
Field
Value
CashBoxId
int
ActivatedBy
int
DeactivatedBy
int
在这种情况下,activatedby 和 deactivatedby 必须与用户 table 相关联。需要知道谁激活了钱箱,谁停用了钱箱。
使用 EF 核心代码优先方法。
具有以下实体模型 -
public class User
{
[Key]
public int UserId { get; set; }
public string UserName { get; set; }
}
public class CashBox
{
[Key]
public int CashBoxId { get; set; }
public int ActivatedBy { get; set; }
public int DeactivatedBy { get; set; }
public User ActivatedUser { get; set; }
public User DeactivatedUser { get; set; }
}
您可以将关系配置为-
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CashBox>(e =>
{
e.HasOne(p => p.ActivatedUser)
.WithMany()
.HasForeignKey(p => p.ActivatedBy);
e.HasOne(p => p.DeactivatedUser)
.WithMany()
.HasForeignKey(p => p.DeactivatedBy);
});
}
在 entity framework 核心中,当两个字段映射到另一个 table 的主键时,我们如何为 table 设置关系。 例如我有两个 table 即 Users & CashBox.
用户Table
Field | Value |
---|---|
UserId | int |
UserName | string |
钱箱Table
Field | Value |
---|---|
CashBoxId | int |
ActivatedBy | int |
DeactivatedBy | int |
在这种情况下,activatedby 和 deactivatedby 必须与用户 table 相关联。需要知道谁激活了钱箱,谁停用了钱箱。
使用 EF 核心代码优先方法。
具有以下实体模型 -
public class User
{
[Key]
public int UserId { get; set; }
public string UserName { get; set; }
}
public class CashBox
{
[Key]
public int CashBoxId { get; set; }
public int ActivatedBy { get; set; }
public int DeactivatedBy { get; set; }
public User ActivatedUser { get; set; }
public User DeactivatedUser { get; set; }
}
您可以将关系配置为-
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CashBox>(e =>
{
e.HasOne(p => p.ActivatedUser)
.WithMany()
.HasForeignKey(p => p.ActivatedBy);
e.HasOne(p => p.DeactivatedUser)
.WithMany()
.HasForeignKey(p => p.DeactivatedBy);
});
}