Search code examples
entity-frameworkentity-framework-6entity-framework-extensions

Entity Framework - Database generated identity is not populated after save if it is not the key of the entity


I have a model like

public class MyEntity
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    public int Id { get; set; } // Id

    [Required]
    [Key]
    public System.Guid GUID { get; set; }
}

The GUID property is the PK by design, but I have a db generated Id property that I use within my code to determine if the object is a new object that hasn't been saved yet.

When I save this object with Entity Framework, the Id property does not get back populated as normally happens for database generated properties (although usually these are keys). I have to query the DB for the object and grab the ID manually. It seems EF only back populates Key properties on SaveChanges.

Is there any way to get EF to automatically populate the Id property here? Setting it as the Key is not an option, I have dozens of tables that are FK'd to the GUID property and for good reason.

EDIT: I have discovered that the package https://entityframework-extensions.net/ is handling my save changes. If I use the standard EF savechanges it works, but not with the extensions version.


Solution

  • Disclaimer: I'm the owner of Entity Framework Extensions

    It was indeed an issue in our library. This scenario was not yet supported for EF6.

    However, starting from the v4.0.50, it should now work as expected.