简体   繁体   English

如何使用EF6 for Web API为域模型创建可选的日志记录属性?

[英]How to create optional logging properties for a domain model using EF6 for a Web API?

I am designing an Web API where I'd like to keep track of the User who created, updated or removed a certain entity with the corresponding methods. 我正在设计一个Web API,我想跟踪使用相应方法创建,更新或删除了某个实体的User。

Usage 用法

  • GET --> Nothing GET->没事
  • POST --> Created POST->已创建
  • PUT --> Created AND Modified PUT->创建并修改
  • DELETE --> Removed 删除->已删除

So you can say Created is mandatory and the Modified + Removed are optional. 因此,您可以说Created是必需的,而Modified + Removed是可选的。

Entities: 实体:

public User {
    public int Id { get; set; }
    public int FirstName { get; set; }
    public int LastName { get; set; }
}

public MyRandomEntity {
    public int Id { get; set; }

    // ...

    public DateTime CreatedDate { get; private set; } //mandatory
    public User CreatedBy { get; private set; } //mandatory

    public DateTime UpdatedDate { get; set; } //optional
    public User UpdatedBy { get; set; } //optional

    public DateTime RemovedAt { get; set; } //optional
    public User RemovedBy { get; set; } //optional
}

I am kinda struggling to get this right. 我有点努力做到这一点。 Complex types cannot be optional by default plus I am using three foreign keys in this model. 默认情况下,复杂类型不能为可选,另外,我在此模型中使用了三个外键。

Is there a way to configure this nicely using FluentApi? 有没有一种方法可以使用FluentApi很好地进行配置? I'd like to point out there is no other entity that requires these same logging properties as I call them. 我想指出的是,没有其他实体需要与我称为它们的相同的日志记录属性。

Thanks in advance 提前致谢

In EF all fields are required if you don't specify that they are nullable. 在EF中,如果您未指定所有字段为空,则所有字段都是必填字段。 Not manditory fields are nullable types example: 非必填字段是可空类型示例:

public MyRandomEntity {
    public int Id { get; set; }

    // ...

    public DateTime CreatedDate { get; private set; } //mandatory
    public User CreatedBy { get; private set; } //mandatory

    public DateTime? UpdatedDate { get; set; } //optional
    public User? UpdatedBy { get; set; } //optional

    public DateTime? RemovedAt { get; set; } //optional
    public User? RemovedBy { get; set; } //optional
}

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

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