1

I have a database where many of the tables have a set of audit data rows:

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

For example, the Area and Citation table both have such a set of rows. The userIds are linked by a foreign key to the User table (as you would expect.)

When I run the EF scaffolding generator (this is a db first project) I run this:

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

When I look at the User class I get this:

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; }
}

(It is actually used in hundreds of tables, but I have abbreviated the above to make it a bit clearer.)

I really don't want to navigate from a user to all the records that use a user in these audit lines, but I don't know what I can do to strip this out or prevent it from being generated. When I get a user from the database I don't want all these extra fields, even if they are null without an include. I guess if I drop the FK relationship that might do it, but that does not seem a good idea at all.

Any suggestions?

TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
Fraser Orr
  • 361
  • 1
  • 3
  • 19

1 Answers1

2

Currently the solution is to customize the generated code after scaffolding. See Customizing the Model.

You can always generate your own models, or try a third-party component like EntityFrameworkCore.Scaffolding.Handlebars

Note that in a hand-built or customized model there's a really cool feature in EF Core for handling this kind of "infrastructure" columns: Shadow Properties

David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67
  • Indeed I think shadow properties are made for this. [Here's](https://stackoverflow.com/a/52021425/861716) an example of what it could look like. – Gert Arnold Feb 14 '19 at 09:34