【问题标题】:Database First EF Core and Inverse Property数据库优先 EF Core 和反向属性
【发布时间】:2019-02-13 21:27:07
【问题描述】:

我有一个数据库,其中许多表都有一组审计数据行:

public Guid CreatedByUserId { get; set; }
public DateTime CreatedDate { get; set; }
public Guid? ModifiedByUserId { get; set; }
public DateTime? ModifiedDate { get; set; }

例如,Area 和 Citation 表都有这样一组行。 userId 通过外键链接到 User 表(如您所料)。

当我运行 EF 脚手架生成器(这是一个 db first 项目)时,我运行这个:

dotnet ef dbcontext scaffold "....connection..." Microsoft.EntityFrameworkCore.SqlServer -o "output" --data-annotations

当我查看 User 类时,我明白了:

public class User
{
    public User()
    {
        AreaCreatedByUser = new HashSet<Area>();
        AreaModifiedByUser = new HashSet<Area>();
        CitationCreatedByUser = new HashSet<Citation>();
        CitationModifiedByUser = new HashSet<Citation>();
    }

    public Guid Id { get; set; }
    [Required]
    [StringLength(50)]
    public string Name { get; set; }
    public Guid CreatedByUserId { get; set; }
    public DateTime CreatedDate { get; set; }
    public Guid? ModifiedByUserId { get; set; }
    public DateTime? ModifiedDate { get; set; }

    public virtual ICollection<Area> AreaCreatedByUser { get; set; }
    [InverseProperty("ModifiedByUser")]
    public virtual ICollection<Area> AreaModifiedByUser { get; set; }
    [InverseProperty("CreatedByUser")]
    public virtual ICollection<Citation> CitationCreatedByUser { get; set; }
    [InverseProperty("ModifiedByUser")]
    public virtual ICollection<Citation> CitationModifiedByUser { get; set; }
}

(其实上百张表都用到了,不过为了更清楚一点,我把上面的做了个缩写。)

我真的不想从用户导航到在这些审计行中使用用户的所有记录,但我不知道我可以做些什么来去除它或阻止它生成。当我从数据库中获取用户时,我不想要所有这些额外的字段,即使它们在没有包含的情况下为空。我想如果我放弃 FK 关系可能会这样做,但这似乎根本不是一个好主意。

有什么建议吗?

【问题讨论】:

    标签: database entity-framework entity-framework-core


    【解决方案1】:

    目前的解决方案是自定义脚手架后生成的代码。见Customizing the Model

    您始终可以生成自己的模型,或尝试使用第三方组件,如EntityFrameworkCore.Scaffolding.Handlebars

    请注意,在手动构建或自定义模型中,EF Core 中有一个非常酷的功能可以处理这种“基础设施”列:Shadow Properties

    【讨论】:

    • 确实,我认为阴影属性是为此而生的。 Here's 一个例子。
    猜你喜欢
    • 2018-09-05
    • 2020-05-22
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多