none
Code first from database does not set the primary keys RRS feed

  • Question

  • I have a Sqlite database and I am using System.Data.Sqlite. I can create the connection and I can create an edmx correctly, the primary key is set.

    However, I would like to create the dbContext from the code first from database option, but in this case in the fluent code, the primary key is not set, however the foreign keys are set and the rest of the configurations seem correct.

    So I am wondering why the primary key is not set, because if in database first option the primary key is set in the edmx, I guess that the problem does not seem to be the System.Data.Sqlite library.

    For example, for one of the entities I have this code:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Entity<CanalesAudio>()
                    .Property(e => e.CanalAudio)
                    .IsUnicode(false);
    
                modelBuilder.Entity<CanalesAudio>()
                    .HasMany(e => e.FicherosAudios)
                    .WithRequired(e => e.CanalesAudio)
                    .HasForeignKey(e => e.IDCanalesAudio)
                    .WillCascadeOnDelete(false);
            }

    As it is shown, settings like delete on cascade, is requiered and foreign keys are set, but not primary key.

    I would like to use my own column names, so I prefer avoid to change the name to follow the name conventions.

    Thank you so much.

    Wednesday, January 13, 2016 10:19 AM

Answers

  • Hi ComptonAlvaro,

    >>As it is shown, settings like delete on cascade, is requiered and foreign keys are set, but not primary key.

    Code first gives us two ways to add these configurations to your classes. One is using simple attributes called DataAnnotations and the other is using code first’s Fluent API, which provides you with a way to describe configurations imperatively, in code. By default, Code first from database primary key use DataAnnotations on entities class.

    One of the conventions that code first depends on is how it implies which property is the key in each of the code first classes. That convention is to look for a property named “Id” or one that combines the class name and “Id”, such as “BlogId”. The property will map to a primary key column in the database.

    Code first from database would add a key attribute on prime key property if it doesn’t follow the convention.

    Best regards

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by ComptonAlvaro Thursday, January 14, 2016 8:04 AM
    Thursday, January 14, 2016 6:15 AM
    Moderator