【问题标题】:Should EF entites contains additional fields? [closed]EF 实体是否应该包含其他字段? [关闭]
【发布时间】:2020-02-19 23:31:21
【问题描述】:

我使用 EntityFramework 作为我的 DAL,例如我有实体:

public class UserEntity
{
    public int WorkingDays {get;set;}
}

我通过存储库在我的服务层中获取此实体,这就是我需要计算的地方,例如他的薪水:

public ???? GetUserWithPayments(int id)
{
    var userEntity = _userRepository.GetUser(id);
    var payPerDieValue = _paymentService.GetValue();

    var salary = userEntity.WorkingDays * payPerDieValue;

  //*what should i return??*//
}

现在我不知道我应该从这个方法返回什么?我看到 2 个选项:

1.) 将薪水字段添加到 UserEntity,并返回 UserEntity。当我将 UserEntity 保存到数据库时,该字段将被跳过。

2.) 使用 UserEntity 字段和另外一个 Salary 创建 UserDto

此服务由 UserController 调用,结果将映射到 GetUserDetailsViewModel

【问题讨论】:

  • 是的,创建一个 DTO/ViewModel。保持实体模型干净(单一职责)。
  • @SteveGreene,我在控制器中获得了 ViewModel。所以存储库应该返回 UserEntity,然后在服务中我应该返回 UserDTO,然后从控制器 UserViewModel。所以我应该有3层模型对吗?每层都有自己的数据模型?

标签: c# asp.net entity-framework design-patterns architecture


【解决方案1】:

您不需要 UserEntity 的薪金属性,因为它会重复数据。最终创建一个属性

[NotMapped]
public decimal Salary => WorkingDays * PayPerDay;

注意它没有被映射,所以它不是插入到数据库中,而是在每次调用时计算的。

附:我看到您使用 int,但对 PayPerDay 使用小数更为自然,因为薪水不必是整数。此外,您还希望包括某人工作半天但仍会获得报酬的可能性。

【讨论】:

  • 嗨,我刚刚编辑了这个问题。这只是理解我的观点的示例实体。
  • 只返回 UserEntity。它将在 UserEntity.Salary 属性中计算薪水。
  • 不会有,再看问题。 UserEntity 中不再有 PayPerDay。我的第一个例子是错误的,现在正确描述了我的问题
  • 你可以返回 Tuple 其中第二个字段是薪水。
猜你喜欢
  • 2023-02-23
  • 1970-01-01
  • 2012-01-25
  • 1970-01-01
  • 2013-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多