EntityFramework Core Fluent Model Builder Key and Property

c# entity-framework entity-framework-core fluent fluent-entity-framework

Question

Ok so in entity framework 6 I would have had a key and property database generation in one statement:

modelBuilder.Entity<Function>()
                .HasKey(x => x.Id)
                .Property(x => x.Id)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

In entity framework core (7) this does not work:

modelBuilder.Entity<Function>()
                .HasKey(x => x.Id)
                .Property(x => x.Id)
                .ValueGeneratedNever();

Error: "'KeyBuilder' does not contain a definition for 'Property' and no extension method 'Property' accepting a first argument of type 'KeyBuilder'":

Does this have to be two separate statements as below or is there a way to have it in one like you could in EF6?

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Function>()
                    .HasKey(x => x.Id);

    modelBuilder.Entity<Function>()
                    .Property(x => x.Id)
                    .ValueGeneratedNever();
}
1
4
1/30/2017 10:40:25 AM

Accepted Answer

Yes, they are separate in EF Core.

The reason is because EF6 method allows you to specify the PK columns and nothing more, hence is returning EntityTypeConfiguration<TEntityType> (the same as the target obtained from Entity<...> call) and that's why you can continue fluently configuring the entity type.

However the EF Core method returns a different type called KeyBuilder which allows you to further configure the PK, like HasName for the relational constraint name, or specific database attributes like ForSqlServerHasName and ForSqlServerIsClustered etc.

4
1/27/2017 4:46:40 PM


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