【问题标题】:What are the ways to make property code-generated only有什么方法可以只生成属性代码
【发布时间】:2020-12-25 18:26:37
【问题描述】:

我正在尝试创建一个包含属性的抽象类,并且我的解决方案中的每个实体都将继承此属性。

我确实希望对抽象类属性进行任何用户修改,但代码所做的更改除外。

我想要达到的目标:

public abstract class SystemEntityBase
{
    /// <summary>
    /// Gets the date when entity was created.
    /// </summary>
    public DateTime Created { get; } = DateTime.UtcNow;

    /// <summary>
    /// Gets the date when entity was last active in the system.
    /// </summary>
    public DateTime LastActive { get; } = DateTime.UtcNow;
}

因为我使用的是只读属性,所以 EntityFrameworkCore 在自动生成迁移脚本时不会将此字段添加到我的数据库表中。

我很好奇在我的情况下,在创建数据库列的同时限制属性的可能解决方案是什么?

【问题讨论】:

  • [ReadOnly(true)] 有帮助吗?
  • 你可能还喜欢this approach

标签: c# entity-framework .net-core entity-framework-core


【解决方案1】:

如果您可以使用 c# 9.0,您应该能够使用仅初始化属性。

【讨论】:

  • Init 属性需要 c# 9 .net 5 或必要 mod-req 类型的手动副本。绝对值得一试 - 我只是说需要的不仅仅是 c# 9。
  • 但用户仍然可以通过new SomeEntity {Created = ....} 设置属性值,据我了解,这不是 OP 想要的。
【解决方案2】:

如果我正确理解了问题 - 您可以尝试使用 Backing Fields。对于您的 Created 属性,它可能看起来像这样(由于某种原因,使用 BackingFieldAttribute 在我的测试 SQLite 和 postgres 设置中对我不起作用,但流畅的 API 可以解决问题):

public class SomeEntity
{
    public DateTime Created => _created

    private DateTime _created = DateTime.UtcNow;    
}

OnModelCreating(ModelBuilder modelBuilder):

 modelBuilder.Entity<SomeEntity>()
     .Property(b => b.Created)
     .HasField("_test");

还可以通过一些反射魔法消除手动设置所有SomeEntity 的需要。

【讨论】:

    猜你喜欢
    • 2014-05-20
    • 2018-11-12
    • 2013-11-10
    • 2010-10-05
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    • 2011-09-22
    • 2016-11-15
    相关资源
    最近更新 更多