Database First EF Core and Inverse Property

database entity-framework entity-framework-core

Question

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?

1
0
2/14/2019 12:37:18 AM

Accepted Answer

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

1
2/14/2019 1:33:48 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow