C# Fluent API Map two properties to same column

Going through all the intellisense suggestions of the PropertyBuilder one method caught my attention: ValueGeneratedOnAddOrUpdate().

From the documentation:

Configures a property to have a value generated when saving a new or existing entity.

Adding this to the PropertyBuilder chain seems to tell the Entity Framework that the value is automatically generated by the database upon saving. Therefore EF excludes this property from it’s query during insert or update. Essentially allowing you to map multiple of these “readonly” properties to the same database column and use them in your queries which is exactly what I asked for in my question. This also allows me to remove the private backing field.

My ClubCategory class now looks like this:

public class ClubCategory : IClubFilterLinker
    public int ClubId { get; set; }

    public int CategoryId { get; set; }

    public int OtherId { get; set; }

And this is the corresponding Fluent API mapping:

    .Property(cc => cc.CategoryId)

    .Property(cc => cc.OtherId)
    // Prevent EF from using this property in insert / update statements.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top